Convert quartely to monthly using formula

6 次查看(过去 30 天)
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 中查找有关 Agriculture 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by