matlabstructcell-array

How to effciently add a field of the same repeated value to a struct array


I have a non-scalar struct array. For example

S=struct;
S(1).f1='a';
S(2).f1='b';

How do I add a field .f2 to S for the same value 1 efficiently? such that S becomes a struct with

S(1).f2=1;
S(2).f2=1;

I would use cell2struct if fields .f1 and .f2 are written at the same time as the creation of S, though without understanding whether it is efficient, via something equivalent to

C={'a','b'};
C(end+1,:)={1};
S=cell2struct(S,{'f1','f2'});

How do you efficiently create the desired S if the different field values are available at different times?

Is there some general trend that helps understanding which syntax/method may be more efficient? Or is the only way to know efficiency is to think of as many methods as possible and test it? (Ofc, one would only commit to such a test if the use case is known to involve a very large array or a moderately large array repeated many times.)


Solution

  • I would use this code. As a general rule, to improve efficiency you should try to avoid cell arrays and explicit loops, using instead standard arrays and vectorization. I haven't tested the code for efficiency, though:

    value = 1;
    [S.f2] = deal(value);
    

    If for the new field you have different values, the code can be generalized to the following. In this case a cell array is necessary:

    values = {1, [10 20; 30 40]};
    [S.f2] = deal(values{:});