6

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?

3 Answers 3

4

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]);
Sign up to request clarification or add additional context in comments.

Comments

3

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

3 Comments

Yeah @Amro, a loop is my plan B. It's just that we've grown up accustomed to the dogma that loops in matlab are bad. With JIT compilation it may not be the case, but I wonder if there is a one line solution.
@jonnat: Vectorization is most useful for heavy computations, yours is a simple assignment statement. So even if you come up with a one-liner, I doubt it will be much faster than this straightforward loop
Maybe its better to use fieldnames in the more general case, instead of manually assign names
0

In simple cases, you could do that by converting your struct into a cell array using struct2cell(). As you have a nested structure, I don't think that will work here.

On the other side, is there any reason why your data is structured like this. Your description gives the impression that a simple MxN array or cell array would be more suitable.

1 Comment

the structure in the example is very simplified. The structure in my code complex and can't be converted to a cell. Even if this was possible, it is part of an API and I can't touch it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.