Why my for loop does not work correctly?
1 回表示 (過去 30 日間)
古いコメントを表示
Hey all,
I had this code below:
for i = 1:numel(Class1_mon_avg_synop) %size of Class1_mon_avg_synop is 1 x 12 cell
ave(i) = Class1_mon_avg_synop{1,i}.sum_rrr24(1); % first row in sum_rrr24 is for January
Jan_class1_avg{i,1} = ave(i);
end
for i = 1:numel(Class1_mon_avg_grid) %size of Class1_mon_avg_grid is 1 x 12 cell
ave(i) = Class1_mon_avg_grid{1,i}.sum_precip(1);% first row in sum_precip is for January
Jan_class1_avg{i,2} = ave(i);
end
% Do same for next month
for i = 1:numel(Class1_mon_avg_synop)
ave(i) = mean(Class1_mon_avg_synop{1,i}.sum_rrr24(2)); % second row in sum_rrr24 is for February
Feb_class1_avg{i,1} = ave(i);
end
for i = 1:numel(Class1_mon_avg_grid)
ave(i) = mean(Class1_mon_avg_grid{1,i}.sum_precip(2)); % second row in sum_rrr24 is for February
Feb_class1_avg{i,2} = ave(i);
end
% do same for all other month
% ...
As I should calculate this for all 12 months then I wrote this for loop:
for i = 1:numel(Class1_mon_avg_synop)
ave(i) = Class1_mon_avg_synop{1,i}.sum_rrr24(i);
ave(i) = Class1_mon_avg_grid{1,i}.sum_precip(i);
ALLMONTHS_class1_avg{i,i} = ave(i);
ALLMONTHS_class1_avg{i,i+1} = ave(i);
end
But unfortunately, I got the wrong answer:

Because I think it must be 12 x 24 cell. 1st and 2nd column for January, 3rd, and 4th for February, etc...
Thank you
回答 (1 件)
Mohammad Sami
2020 年 4 月 1 日
編集済み: Mohammad Sami
2020 年 4 月 1 日
for i = 1:numel(Class1_mon_avg_synop)
j = (i-1)*2;
ave(i) = Class1_mon_avg_synop{1,i}.sum_rrr24(i);
ALLMONTHS_class1_avg{i,j+1} = ave(i);
ave(i) = Class1_mon_avg_grid{1,i}.sum_precip(i); % this will overwrite ave(i)
ALLMONTHS_class1_avg{i,j+2} = ave(i);
end
note: your code was overwriting ave(i) value. i left it as it is as i don't know what was your intention.
4 件のコメント
dpb
2020 年 4 月 2 日
Missed the response until now, sorry...
OK. I got the want; how about also attaching a .mat file with the data so can play without having to try to reconstruct something to test with. Looks likely the storage is overly complex for the problem but that's also hard to tell quickly just by reading...
参考
カテゴリ
Help Center および File Exchange で Multidimensional Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!