Calculate monthly averages without reshaping

조회 수: 1 (최근 30일)
aaron Harvey
aaron Harvey 2016년 2월 18일
편집: Stephen23 2016년 2월 24일
i have a time series of data and i would like to calculate monthly averages but keeping the vector lengths the same. (the variables also contain many nans)
For example if i have a date vector (yyyymm):
date=
199901
199901
199901
199905
199905
200107
200107
200107
variable=
1
2
3
4
5
5
6
7
How can i get
variable_montlyav=
2
2
2
4.5
4.5
6
nan (or 6 i dont mind)
6
so that i can use my new montly averaged variable with some existing codes i have.
  댓글 수: 1
Stephen23
Stephen23 2016년 2월 22일
편집: Stephen23 2016년 2월 24일
What exactly do you mean by a "date vector"? In MATLAB the term "date vector" has a specific meaning, which is a numeric vector consisting |y,m,d,H,M,S.F] values. If your data really was a date vector, it would looks like this:
1999 1 1 0 0 0
1999 1 1 0 0 0
1999 1 1 0 0 0
1999 5 1 0 0 0
1999 5 1 0 0 0
2001 7 1 0 0 0
2001 7 1 0 0 0
2001 7 1 0 0 0

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2016년 2월 22일
편집: Stephen23 2016년 2월 24일
Note: this code works if date is a cell array of strings, and also if date is a numeric vector of values representing year and month.
date = {'199901','199901','199901','199905','199905','200107','200107','200107'};
variable = [1,2,3,4,5,5,6,7];
[~,~,idx] = unique(date);
tmp = accumarray(idx(:), variable, [], @mean);
tmp(idx)
creates this output:
ans =
2.0000
2.0000
2.0000
4.5000
4.5000
6.0000
6.0000
6.0000
  댓글 수: 1
aaron Harvey
aaron Harvey 2016년 2월 23일
worked perfectly! i dunno how it works but it does :)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Roger Wohlwend
Roger Wohlwend 2016년 2월 22일
A = accumarray(date, variable, [], @mean);
MeanValues = A(date);
  댓글 수: 1
Stephen23
Stephen23 2016년 2월 22일
This is not a very memory-efficient solution, as it will create temporary arrays with more than 200000 elements in them. See my answer for a more memory-efficient solution.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Line Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by