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

1 view (last 30 days)
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) = max(data(j)) = min(data(j))
I don't know how to create the fields - and - of the the structure s using the entires in the array data. Can someone please help me?

Accepted Answer

Stephen23 on 8 Jan 2022
Edited: Stephen23 on 10 Jan 2022
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});
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);
Allen Hammack
Allen Hammack on 12 Jan 2022
Thank you for the suggestion about num2str being slow. I replaced num2str with your suggestion of using %d, and the script is much faster.

Sign in to comment.

More Answers (0)


Find more on Loops and Conditional Statements 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!

Translated by