how to grab the last value in a loop?

조회 수: 5 (최근 30일)
Fabian Moreno
Fabian Moreno 2021년 4월 11일
댓글: Fabian Moreno 2021년 4월 13일
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

채택된 답변

Jan
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
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, []).';
Fabian Moreno
Fabian Moreno 2021년 4월 13일
wow, Jan you´re awesome, I´m feel so happy doing that. Thank you, you taught me a lot. I would like to learn more! I´m pretty sure that matlab should has amazing things.
Gracias!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by