How can I create structure entries in a for loop.?

조회 수: 42 (최근 30일)
Allen Hammack
Allen Hammack 2022년 1월 8일
댓글: Allen Hammack 2022년 1월 12일
I have multiple data sets. For each data set, I would like to perform multiple calculations and have the results of those calculations be entries in a structure. For instance, say I have three data sets for which I'd like to calculate the maximum and minimum values and create entries in a fields in a structure for each maximum and minimum. I'm currently doing these calculations for each data set separately without a for loop, and my code is repetitive. I think I should be able to do this, but I haven't been able to figure out how. I think my code should look something like this:
data = [data1 data2 data3]
for j = length(data)
s.data(j)_max = max(data(j))
s.data(j)_min = min(data(j))
end
I don't know how to create the fields - s.data(j)_max and s.data(j)_min - of the the structure s using the entires in the array data. Can someone please help me?

채택된 답변

Stephen23
Stephen23 2022년 1월 8일
편집: Stephen23 2022년 1월 10일
Using a cell array and a structure array:
C = {data1,data2,data3};
for k = 1:numel(C)
S(k).max = max(C{k});
S(k).min = min(C{k});
end
Or one structure array (more robust, recommended):
S = struct('data',{data1,data2,data3});
for k = 1:numel(S)
S(k).max = max(S(k).data);
S(k).min = min(S(k).data);
end
  댓글 수: 7
Stephen23
Stephen23 2022년 1월 12일
편집: Stephen23 2022년 1월 12일
It is simpler to use the %d format specifier, rather making things more complex by adding slow NUM2STR:
sprintf('%d_max',k)
% ^ ^
"Your obfuscated code also works with a slight modification."
Structure fieldnames must start with a letter, so your modification will not work:
S = struct();
S.(sprintf('%d_max',2)) = pi
Invalid field name: '2_max'.
Using the fieldnames that I showed you however does work, as they have leading letters.
Allen Hammack
Allen Hammack 2022년 1월 12일
Thank you for the suggestion about num2str being slow. I replaced num2str with your suggestion of using %d, and the script is much faster.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by