How to write a loop for this purpose?

1 view (last 30 days)
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
Daniel M
Daniel M on 27 Oct 2019
Edited: Daniel M on 27 Oct 2019
I refuse to encourage this type of coding. (And those are invalid names for variables anyways).
BN
BN on 27 Oct 2019
ok I understand you.
so you mean that I should type every 34 years by my hand instead of using loop, right?

Sign in to comment.

Accepted Answer

Walter Roberson
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
BN
BN on 27 Oct 2019
Thank you, Walter, for letting me know that this is a bad idea. I saw some alternative ways in
but the content of my precips cell is 3d arrays, like:
precips{1, 1}= 720*360*365 (see the screenshot attached)
I just want to export these 3d arrays inside precips to my workplace, in order to use in the rest of calculation code. do you know any other better way?
actually:
for iter = 1 : size(precips,1)
year = 1981 + iter;
cmd = sprintf('%d = precips{%d,1}', year, iter);
eval(cmd);
end
gaves me following error:
Error: Incorrect use of '=' operator. To assign a value to a variable,
use '='. To compare values for equality, use '=='.
I want to do all these things in order to convert 34 NetCDF files that are in a daily basis (from 1982 to 2015) to monthly some for each year and then use them to build one comprehensive 3d array for all period of 1982-2015.
many thanks
Walter Roberson
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.

Sign in to comment.

More Answers (0)

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!