Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simultaneously assign values to multiple structure fields

Tags:

matlab

I have a matlab structure that follows the following pattern:

S.field1.data1
          ...
 .field1.dataN
   ...
 .fieldM.data1
          ...
 .fieldM.dataN

I would like to assign values to one data field (say, data3) from all fields simultaneously. That would be semantically similar to:

S.*.data3 = value

Where the wildcard "*" represents all fields (field1,...,fieldM) in the structure. Is this something that can be done without a loop in matlab?

like image 489
foglerit Avatar asked Oct 26 '11 20:10

foglerit


2 Answers

Since field1 .. fieldM are structure arrays with identical fields, why not make a struct array for "field"? Then you can easily set all "data" members to a specific value using deal.

field(1).data1 = 1;
field(1).data2 = 2;
field(2).data1 = 3;
field(2).data2 = 4;

[field.data1] = deal(5);
disp([field.data1]);
like image 158
Rich C Avatar answered Oct 25 '22 02:10

Rich C


A loop-based solution can be flexible and easily readable:

names = strtrim(cellstr( num2str((1:5)','field%d') ));    %'# field1,field2,...
values = num2cell(1:5);                                   %# any values you want

S = struct();
for i=1:numel(names)
    S.(names{i}).data3 = values{i};
end
like image 38
Amro Avatar answered Oct 25 '22 02:10

Amro