# Sum the daily data based on month and year

59 views (last 30 days)
Ryn on 29 Apr 2019
Answered: ABHILASH SINGH on 13 Mar 2020
I have a three dimensional matrix of gridded data (16x18x7669) where 16 is the latitudes, 18 the longitudes and 7669 is the daily data from 1/1/1998 to 31/12/2018. I would like to get the monthly and yearly totals for each grid. I am a newbie in Matlab and I will appreciate suggestions on how to go about it. Thank you in advance

Stephane Dauvillier on 29 Apr 2019
Edited: Stephane Dauvillier on 29 Apr 2019
Lets assume your 3D variable is called data
Frist get the group id : which width of data correspond to the same month of the same year:
time=datetime(1998,1,1):datetime(2018,12,31);
grp = findgroups(year(time),month(time));
Then cget the unique list of group
uniqueGr = unique(grp);
Initialize the result and loop on unique groupe element
result = zeros(size(data,1),size(data,2),numel(uniqueGr)) ;
for iGroup = 1:numel(uniqueGr)
Compute the sum on the 3rd dimension but only for the data which corresponding date to the current group
result(:,:,iGroup) = sum(data(:,:,grp==uniqueGr(iGroup)),3);
end
Note there is the function splitapply that makes this easier if you have 2D array

Ryn on 30 Apr 2019
Hi Stephane,
This works but Iam getting unrealistic values and I cannot figure out what I am doing wrong. This is what I have tried for the yearly totals:
clear;close all;clc;
%%yearlytotals
yGroup = findgroups(year(dateCHIRPS));
uniqueGrYr=unique(yGroup);
%Initialize the result and loop on unique groupe element
pCHIRPS_Y=zeros(size(precipCHIRPS2,1),size(precipCHIRPS2,2),numel(uniqueGrYr));
for iGroup = 1:numel(uniqueGrYr)
pCHIRPS_Y(:,:, iGroup) = sum (precipCHIRPS2 (:,:, yGroup == uniqueGrYr (yGroup)), 3);
end
Stephane Dauvillier on 30 Apr 2019
What do you mean by "unrealistic values" ?
You ask to sum the whatever data you have for each year.
Let's just take a tiny example
years = [1990,1990,1991];
data(:,:,1) = [1,2;3,4;5,6] ;
data(:,:,2) = [7,8;9,10;11,12];
data(:,:,3) = [13,14;15,16;17,18];
Then you will have as a result
for year 1990
result(:,:,1) = data(:,:,1) + data(:,:,2) = [8,10;12,14;16,18]
and for year 1991
result(:,:,2) = data(:,:,3) = [13,14;15,16;17,18];
Ryn on 2 May 2019
Thank you Stephane