How can I assign values to a Structure with multiple subfields with one line of code?
조회 수: 23 (최근 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
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
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?
댓글 수: 0
추가 답변 (1개)
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()
[ExampleStruct.SubField1 ExampleStruct.SubField2 ExampleStruct.SubField3 ExampleStruct.SubField4] = deal([]);
ExampleStruct
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!