Monthly sum function with nansum not being used correctly
Show older comments
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 Comments
Mathieu NOE
on 8 Nov 2022
hello
why not use this kind of code ?
here the data are organized as [date (yyyymmdd) rain fall data]

This is a typical example where you can use table instead of matrix.
A = [19260702 0.026 0.000 NaN 1.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 = varfun(@sum,T,'InputVariables',{'S1','S2','S3','S4'},'GroupingVariables','MONTH')
Augusto Gabriel da Costa Pereira
on 8 Nov 2022
Mathieu NOE
on 9 Nov 2022
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')
Accepted Answer
More Answers (0)
Categories
Find more on Dates and Time 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!