Convert quartely to monthly using formula

14 views (last 30 days)
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?

Accepted Answer

Chunru
Chunru on 23 Jul 2022
Edited: Chunru on 23 Jul 2022
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, []))';

More Answers (0)

Categories

Find more on Migrate GUIDE Apps in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by