Convert quartely to monthly using formula

조회 수: 4 (최근 30일)
alphabetagamma
alphabetagamma 2022년 7월 23일
댓글: alphabetagamma 2022년 7월 23일
I am having trouble with converting monthly to quarterly observations using the formula below.
n = 3; % 3 months in a quarter
num_quarterly_obs = 158
num_monthly_obs = 457
% as the data is monthly, we convert it to quarterly
% take average of every three values (or three months in a quarter)
% and save that number in a new vector called var_quar
% So, var_quar has quarterly observations where each observation is an
% average of three months prior
% should have 158 quarterly observations
var_quar = arrayfun(@(i) mean(var_monthly(i:i + n -1)), 1:n:n*num_quarterly_obs - n+1)';
The error message is:
Index exceeds the number of array elements. Index must not exceed 457.
Ideally, var_quar should have 158 observations. Funnily, when I replace num_quartery_obs = 152 in the formula obove, the code works but size(var_quar) is 152 which is not desired. How can I resolve this error?

채택된 답변

Chunru
Chunru 2022년 7월 23일
편집: Chunru 2022년 7월 23일
Since you have 457 months of observation, which is not integer multiples of 3 months or quaaters. You have to decide to what to do with the last parts of 2months (457=152*3+1). A simple way is not counting the last quarter.
n = 3; % 3 months in a quarter
num_quarterly_obs = 158;
num_monthly_obs = 457;
var_monthly = randn(num_monthly_obs, 1);
% as the data is monthly, we convert it to quarterly
% take average of every three values (or three months in a quarter)
% and save that number in a new vector called var_quar
% So, var_quar has quarterly observations where each observation is an
% average of three months prior
% should have 158 quarterly observations
%var_quar = arrayfun(@(i) mean(var_monthly(i:i + n -1)), 1:n:n*num_quarterly_obs - n+1)';
var_quar = mean(reshape(var_monthly(1:456), 3, []))';

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Random Number Generation에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by