MATLAB Answers

monthly average of my variables

1 view (last 30 days)
INGRUS
INGRUS on 12 Dec 2019
Answered: Cris LaPierre on 18 Mar 2020
I have two vectors one for dates and one for values. My years are between 2009 and 2019, and I would like to take the monthly average for each year, but I have one or two values ​​per month. I have created a little code, but it doesn't show what I want. can you help me?
m=load(['xxx.mat']);
date=m.DateArray
dati=xlsread('p20','B1:B82');
dn=datenum('01-01-2009','dd-mm-yyyy'):datenum('31-12-2019','dd-mm-yyyy')
swh=randi(10,numel(dn),1)
[y,m,d] = datevec(dn);
a=[y' m' d']
[ii,jj,kk]=unique(a(:,1:2),'rows')
out=accumarray(kk,(1:numel(kk))',[],@(x) mean(swh(x)))
k=0;
for j = [2009:2019]
for i= [1:12]
k=k+1;
idx=find(y==j&m==i);
out1(k)=mean(swh(idx));
end
end

  0 Comments

Sign in to comment.

Answers (1)

Cris LaPierre
Cris LaPierre on 18 Mar 2020
Recommendations would be to use readtable, add a variable to the table containing the dates as datetimes, and then use groupsummary to create a sumary table that averages your data by month. Here's an example from the doc since we don't have your actual variables.
TimeStamps = datetime([2017 3 4; 2017 3 2; 2017 3 15; 2017 3 10;...
2017 3 4; 2017 3 31; 2017 3 15;...
2017 3 2; 2017 3 31; 2017 3 10]);
Profit = [2032 3071 1185 2587 1998 2899 3112 909 2619 3085]';
TotalItemsSold = [14 13 8 5 10 16 8 6 7 11]';
TT = table(TimeStamps,Profit,TotalItemsSold);
avgTT = groupsummary(TT,'TimeStamps',"day",'mean','Profit')

  0 Comments

Sign in to comment.

Sign in to answer this question.


Translated by