Monthly sum function with nansum not being used correctly

조회 수: 3 (최근 30일)
Augusto Gabriel da Costa Pereira
댓글: Mathieu NOE 2022년 11월 9일
I use the function below to perform the monthly precipitation accumulator, however, when there are days without NaN measurements in a given month, the result for that month is zero. But this result is wrong, the correct series for this month is NaN and not zero.
Another problem seen in the function is the result of months. From January 2000 to December 2020 there are 252 months. when I use the function, the result is only 251 months, that is, one month to go
Below is:
1 - the function used for the monthly sum.
2 - rainfall data, in column 1 the days of the year and in columns 2, 3, 4 and 5 the rainfall (INMET_Diario.mat);
function Y = monthly_sum(time_X,X)
[l,c] = size(X);
grp = [];
for y = 2000:2020 % Change period here
for m = 1:12
grp = [grp datenum(y,m,1)];
end
end
X_hour = zeros(length(grp)-1,c);
for i = 1:length(grp)-1
if(mod(i,500)==0)
disp(i)
end
for j = 1:c
X_hour(i,j) = nansum(X(time_X>=grp(i) & time_X<grp(i+1),j));
end
end
Y = [grp(1:length(grp)-1)', X_hour];
Best Regards,
AP
  댓글 수: 3
Augusto Gabriel da Costa Pereira
If my goal is to AVERAGE, replace @sum with @mean on the last line?
Mathieu NOE
Mathieu NOE 2022년 11월 9일
yes that works also
A = [19260702 0.026 0.000 NaN 1.175
19260705 0.036 0.002 NaN 2.175
19260715 0.044 0.003 NaN 3.175
19260816 0.042 0.007 NaN 25.928];
% Matrix to table conversion
T = array2table(A,'VariableNames',{'DATE','S1','S2','S3','S4'});
% We add a new column "month"
T.MONTH = floor(T.DATE/100);
% varfun can apply a custom function to your table and group the result according
% to one (or more) variable(s)
Result_sum = varfun(@sum,T,'InputVariables',{'S1','S2','S3','S4'},'GroupingVariables','MONTH')
Result_mean = varfun(@mean,T,'InputVariables',{'S1','S2','S3','S4'},'GroupingVariables','MONTH')

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

채택된 답변

Jan
Jan 2022년 11월 8일
편집: Jan 2022년 11월 8일
function Y = monthly_sum(T, X)
grp = [datenum(2000, 1:252, 1), Inf];
ngrp = numel(grp) - 1;
c = size(X, 2);
X_hour = nan(ngrp, c);
for i = 1:ngrp
for j = 1:c
TX = X(T >= grp(i) & T < grp(i+1), j);
if ~isempty(TX)
X_hour(i,j) = nansum(TX);
end
end
end
Y = [grp(1:ngrp).', X_hour];
end
  댓글 수: 2
Augusto Gabriel da Costa Pereira
thank you Jan
problem fully resolved
Jan
Jan 2022년 11월 8일
You are welcome.
datenum(2000, 1:252, 1) is tricky, but working fine.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by