How can I assign values to a Structure with multiple subfields with one line of code?

30 次查看(过去 30 天)
% 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 个评论
Stephen23
Stephen23 2022-4-5
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.

请先登录,再进行评论。

采纳的回答

Jan
Jan 2022-4-5
编辑:Jan 2022-4-5
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?

更多回答(1 个)

Bruno Luong
Bruno Luong 2022-4-5
编辑:Bruno Luong 2022-4-5
Not sure about your claim of one statement is faster than for loop. Whatever here is oneline code
Exampe = struct()
Exampe = struct with no fields.
[ExampleStruct.SubField1 ExampleStruct.SubField2 ExampleStruct.SubField3 ExampleStruct.SubField4] = deal([]);
ExampleStruct
ExampleStruct = struct with fields:
SubField1: [] SubField2: [] SubField3: [] SubField4: []

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by