Monthly sum function with nansum not being used correctly

1 visualización (últimos 30 días)
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 comentarios
Augusto Gabriel da Costa Pereira
Augusto Gabriel da Costa Pereira el 8 de Nov. de 2022
If my goal is to AVERAGE, replace @sum with @mean on the last line?
Mathieu NOE
Mathieu NOE el 9 de Nov. de 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')

Iniciar sesión para comentar.

Respuesta aceptada

Jan
Jan el 8 de Nov. de 2022
Editada: Jan el 8 de Nov. de 2022
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 comentarios
Augusto Gabriel da Costa Pereira
Augusto Gabriel da Costa Pereira el 8 de Nov. de 2022
thank you Jan
problem fully resolved
Jan
Jan el 8 de Nov. de 2022
You are welcome.
datenum(2000, 1:252, 1) is tricky, but working fine.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Dates and Time en Help Center y File Exchange.

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by