How to write a loop for this purpose?
1 view (last 30 days)
Show older comments
Hey all,
I have a 34*1 cell (let's call it precips). I would like to have a loop in order to do this:
1982 = precips {1, 1};
1983= precips {2, 1};
1984= precips {3, 1};
1985= precips {4, 1};
.
.
.
2015= precips {34, 1};
what is the code for the loop?
4 Comments
Accepted Answer
Walter Roberson
on 27 Oct 2019
for iter = 1 : size(precips,1)
year = 1981 + iter;
cmd = sprintf('%d = precips{%d,1}', year, iter);
eval(cmd);
end
3 Comments
Walter Roberson
on 28 Oct 2019
There error is to be expected.
1982 = precips {1, 1};
is not a permitted syntax. But you didn't care about that earlier: you just wanted to know how to write the code to do it anyhow, so I wrote the code to do it anyhow.
I just want to export these 3d arrays inside precips to my workplace, in order to use in the rest of calculation code.
They already are inside your workspace.
num_years = size(precips,1);
all_sums = zeros(720, 360, num_years, 12);
for iter = 1 : num_years
thisdata = permute(precips{iter,1}, [3 1 2]);
year = 1981 + iter;
ts = datetime([year, 1, 0]) + days(1:size(thisdata,1)).'; %column vector
G = month(ts);
month_sum = permute(splitapply(@sum, thisdata, G), [2 3 4 1]);
all_sums(:,:,iter,:) = month_sum;
end
all_sums should now be a 720 x 360 x 34 x 12 array, where the 4th dimension is the month number.
It is not immediately obvious how you want to order the per-month data for all years into a 3D array.
More Answers (0)
See Also
Categories
Find more on Data Type Conversion 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!