user1635485
user1635485

Reputation: 11

Struct with variable length with Matlab

I am collecting data from a process in a struct as follows;

timepace(1,i) = struct(...
    'stageNo',str2num(stageNo), ...
    'split1', splits(1,1),...
    'split2', splits(1,2),...
    'split3', splits(1,3) );

However, the number of “splits” is can vary from 2 to 10. At the moment I am using a longer code than shown above to allocate all the “splits” and if not, put a 0. But this makes me create a lot of unused data for the “just in case” situation of having so many splits. Would there be a way to make the length of it flexible? I know the required final number because it is an input to the system for each query that I do.

Any ideas on how to make it flexible and related to a length variable?

Upvotes: 1

Views: 813

Answers (3)

bdecaf
bdecaf

Reputation: 4732

You could also use cell2struct:

 labels = {'split1','split2','split3',...}
 c = num2cell(splits);
 f = labels(1:numel(c));
 s = cell2struct(c,f,2);

Upvotes: 0

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

Just use an array instead of struct:

timepace(1,i) = struct(...
    'stageNo',str2num(stageNo), ...
    'split',  *PUT HERE YOUR ARRAY*...
);

Don't forget that in the case of cell array, you need additional {} brackets.

timepace(1,i) = struct(...
    'stageNo',str2num(stageNo), ...
    'split',  {{1,2,3,4,5}}...

);

If you must use struct than see Rodys answer.

Upvotes: 0

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

You could use something like

S = struct('stageNo',str2num(stageNo));

for jj = 1:size(splits,2)
    S.(['split' num2str(jj)]) = splits(1,jj);
end

timepace(1,i) = S;

It's called "dynamic field reference". You can find more information here for instance.

Upvotes: 2

Related Questions