how to grab the last value in a loop?
조회 수: 5 (최근 30일)
이전 댓글 표시
Hi there, I would like to know how to get the last value of my loop. I am intersecting a matrix of 35 years of data with a matrix of 420 (420 months, from jan-1985 to dez-2019), where (B) is the intersect position. I am getting the mean value of the sine each 12 month, but in the last value (month 420) the result is NaN. How they are month, it has 31, 30, 29 and 28 days. So I also try to do and If statment, but it didn´t work. Some body could help me.
With the first example I got from 1 to 419 the nanmean values, but the 420 value don´t.
Thak you in advance.
%% first example
seno_m = NaN(length(Date_wd_monthly),1);
for i = 1:420
seno_m(i,1)= nanmean(sin(Date_wd_daily(B(i):B(i)-1,9)));
end
%% Example of the If statment
seno_m = NaN(length(Date_wd_monthly),1);
for i = 1:420
if numel(Date_wd_daily(B(i):B(i+1)-1,9))==31
seno_m(i,1)= nanmean(sin(Date_wd_daily(B(i):B(i,1)+31,9)));
elseif numel(Date_wd_daily(B(i):B(i+1)-1,9))== 30
seno_m(i,1)= nanmean(sin(Date_wd_daily(B(i):B(i,1)+30,9)));
elseif numel(Date_wd_daily(B(i):B(i+1)-1,9))== 29
seno_m(i,1)= nanmean(sin(Date_wd_daily(B(i):B(i,1)+29,9)));
else numel(Date_wd_daily(B(i):B(i+1)-1,9))== 28
seno_m(i,1)= nanmean(sin(Date_wd_daily(B(i):B(i,1)+28,9)));
end
end
댓글 수: 0
채택된 답변
Jan
2021년 4월 11일
In your first code:
seno_m(i,1)= nanmean(sin(Date_wd_daily(B(i):B(i)-1,9)));
% ^^^^ ^^^^^^
This is the empty matrix in all cases. B(i):B(i)-1 does not contain any elements.
Teh 2nd code can be simplified:
seno_m = NaN(length(Date_wd_monthly),1);
for i = 1:420
n = numel(Date_wd_daily(B(i):B(i+1)-1,9));
seno_m(i,1)= nanmean(sin(Date_wd_daily(B(i):B(i,1) + n, 9)));
end
This can be expressed easier also, because numel(Date_wd_daily(B(i):B(i+1)-1,9)) is the same as:
numel(B(i):B(i+1)-1)
which is the same as:
B(i+1) - B(i);
If this equals 31, remember that B(i):B(i,1)+31 contains 32 elements (not 31).
To understand, what your code does and what it should do, the readers need to know what B contains.
댓글 수: 6
Jan
2021년 4월 13일
You can omit the find() for a faster logical indexing:
idx = ((Date_wd_daily(:,2) == i) & (Date_wd_daily(:,3) == j));
You do not need a loop for the conversion:
QD_month = reshape(seno_m(:, 2), 12, []).';
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!