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에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!