How to get monthly average from daily data?
40 次查看(过去 30 天)
显示 更早的评论
So i have this Matrix, consisting of 4 columns: Column 1: Year Column 2: Month Column 3: day (1 to 30) Column 4: Some Value
I want to make monthly average of "some value" without breaking the matrix into some new matrix and calculate mean for each moths matrix seperately then rejoin them. I want to make an average matrix using for loop and find function for each myear seperately. So I dont like to have an average from all the first months of all the years together. Does anyone have an Idea?
I have sth like this, but i donno why it is not working:
k=1
%Calculating Monthly Average
for i=1961:1990 %Years Looping
for j=1:12 %Months Looping
idx=find((date(:,1)==i) & (date(:,2)==j)); %Find all indeces for the specific month
meandata1=mean(date(idx,4),1);
Monthly_Ave(k,:)=[i,j,meandata1;]; %Store in a new matrix the mean values per month
k=k+1;
end
end
5 个评论
采纳的回答
jonas
2018-9-27
编辑:jonas
2018-9-27
Not sure what you mean by "without breaking the matrix into some new matrix", but here we go:
x is column with months,
y is data
[G,name] = findgroups(x)
out = splitapply(@mean,y,G)
This will give you max 12 values, one for each month of the year. If you have several years, and you want 12 values per year, then you can do the following trick.
x1 is months (double)
x2 is years (double)
x=cellstr(num2str([x1, x2]))
[G,name] = findgroups(x)
out = splitapply(@mean,y,G)
Better yet, put your data in a timetable and use retime to calculate the monthly average. Here's an example using your data:
data=xlsread('data.xlsx')
t=datetime(data(:,1:3))
T=timetable(t,data(:,4))
T2=retime(T,'monthly','mean')
更多回答(1 个)
KSSV
2018-9-27
Let M be your month column, extracted and A be your data.
B = zeros(12,1) ; % means
for i = 1:12
B(i) = mean(A(M==i)) ;
end
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Preprocessing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!