how to grab the last value in a loop?
5 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Jan
on 11 Apr 2021
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 Comments
Jan
on 13 Apr 2021
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, []).';
More Answers (0)
See Also
Categories
Find more on Matrices and Arrays 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!