How can I assign values to a Structure with multiple subfields with one line of code?
17 views (last 30 days)
Show older comments
% Hi I want to assign values with different sizes to a structure with subfields respectively. However I want to do it with one line of code due to running speed issues.
% I will try to write the code as simple as possible. Lets say I have a structure with 4 subfields
ExampleStruct.SubField1 = [];
ExampleStruct.SubField2 = [];
ExampleStruct.SubField3 = [];
ExampleStruct.SubField4 = [];
% Now I will create a cell array with 4 cells
CellArr = {[1,2,3,4], [1:10], ['Man of Numenor'], ['Matlab is Great']};
% I can make it with for loop like this
FieldNames = fieldnames(ExampleStruct);
for i=1:length(FieldNames)
ExampleStruct.(FieldNames{i}) = CellArr{i};
end
% But I dont want to do it, because for this code time consuming is large when subfield numbers are 1000 or more.
% How can I make what this for loop does in one line of code ?
% I tried arrayfun and similar approaches with the function handle @(x) that I created, but I couldn't find the answer.
% Could you please help me? I would be very appreciated
1 Comment
Stephen23
on 5 Apr 2022
I doubt that you will find a more efficient approach than using a FOR-loop.
The approach not robust: consider that fieldnames are ordered, then if their order changes the wrong data will get allocated from the cell array. It is a bit smelly: https://en.wikipedia.org/wiki/Code_smell
Note that if you used a non-scalar structure with one field it could be easily achieved using a comma-separated list.
Accepted Answer
Jan
on 5 Apr 2022
Edited: Jan
on 5 Apr 2022
You mention "as simple as possible". Then avoid unneeded operators e.g. by replaing:
CellArr = {[1,2,3,4], [1:10], ['Man of Numenor'], ['Matlab is Great']};
by
CellArr = {[1,2,3,4], 1:10, 'Man of Numenor', 'Matlab is Great'};
[] is Matlab operator for the concatenatoin of arrays. 1:10 is a vector already and [1:10] concatenates it with nothing. This is a wate of time only.
This is the compact way:
Fields = {'SubField1', 'SubField2', 'SubField3', 'SubField4'};
CellArr = {[1,2,3,4], 1:10, 'Man of Numenor', 'Matlab is Great'};
ExampleStruct = cell2struct(CellArr(:), Fields(:));
"1000 subfields" sounds like a bad design. Can you keep the overview over typos in such a huge struct?
0 Comments
More Answers (1)
Bruno Luong
on 5 Apr 2022
Edited: Bruno Luong
on 5 Apr 2022
Not sure about your claim of one statement is faster than for loop. Whatever here is oneline code
Exampe = struct()
[ExampleStruct.SubField1 ExampleStruct.SubField2 ExampleStruct.SubField3 ExampleStruct.SubField4] = deal([]);
ExampleStruct
0 Comments
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!