How to average monthly data using a specific method in Matlab?

조회 수: 1 (최근 30일)
Reginald Pofter
Reginald Pofter 2021년 5월 6일
댓글: Reginald Pofter 2021년 5월 6일
I have the following vector of monthly values (vectorA). I put the date related info next to it to help illustrate the task but I work with just the vector itself
dates month_in_q vectorA
31/01/2020 1 10
29/02/2020 2 15
31/03/2020 3 6
30/04/2020 1 8
31/05/2020 2 4
30/06/2020 3 3
vectorA = [10;15;6;8;4;3]
How can I create a new vectorNEW according to this algorithm
  • In each quarter the first month is the original first month
  • In each quarter the second month is the average of first and second month
  • In each quarter the third month is the average of all three months
So that I get the following vectorNEW by manipulating the original vectorA in a loop given this the re-occuring pattern above
vectorNEW = [10;12.5;10.3;8;6;5]
dates month_in_q vectorA vectorNEW
31/01/2020 1 10 10
29/02/2020 2 15 AVG(10+15)
31/03/2020 3 6 AVG(10+15+6)
30/04/2020 1 8 8
31/05/2020 2 4 AVG(8+4)
30/06/2020 3 3 AVG(8+4+3)
... ... ... ...

채택된 답변

dpb
dpb 2021년 5월 6일
편집: dpb 2021년 5월 6일
There may be a more clever way, but brute force seems straightforward enough...
A=reshape(vectorA,3,[]); % temporary to get 3-row array
mnV=reshape([A(1,:); mean(A(1:2,:)); mean(A(1:3,:))],[],1); % build desired means, turn to column vector
clear A % remove temporary array
AHA! The "more better" way just dawned...knew had to be a cumsum in here somewhere...
mnV=reshape(cumsum(reshape(vectorA,3,[]))./[1:3].',[],1);
  댓글 수: 1
Reginald Pofter
Reginald Pofter 2021년 5월 6일
Thank you, you're spot on. I'll also credit you on stackoverflow with a link to your answer here. I asked the same question there as well.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by