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

22 ビュー (過去 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 Center および File ExchangeStructures についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by