我想根据经济衰退时期对表示日期的序列号数组进行子集化,以便我可以在这些时段内计算mean()
。以下示例说明了这一点:
DateArray = transpose((1:20000)+678420);
RndData = normrnd(0.003,0.05,19999,1);
CumData = cumprod([1;RndData+1]);
Data = [DateArray CumData];
load Data_Recessions.mat %Native `Econometrics toolbox` dataset
% This loads a 2 column double array of start dates in the first column and corresponding end dates in the second column.
plot(Data(:,1),Data(:,2))
set(gca(),'Yscale','log');
recessionplot()
因此我想在上面的灰色条上计算mean()。表示这些期间的日期位于“经济衰退”数组中。我如何最有效地完成这项工作?
答案 0 :(得分:1)
这将为您提供灰色和白色时段的平均值。它构建了一个索引,用作每个数据值的标签,然后应用accumarray
来平均所有具有相同标签的值:
ind = sum(bsxfun(@ge, Data(:,1).', [0; reshape(Date_Recessions.',[],1)]),1)
result = accumarray(ind(:), Data(:,2), [], @mean);
答案 1 :(得分:1)
假设您的衰退日期位于名为D
的2列矩阵中M = arrayfun(@(x)(mean(Data(find(Data(:,1)==D(x,1)):find(Data(:,1)==D(x,2)),2))), 1:size(D,1))
或者作为一个实际上可能更有效的for循环:
M = NaN(size(D,1),1);
for x = 1:size(D,1)
first = find(Data(:,1)==D(x,1))
last = find(Data(:,1)==D(x,2))
M(x) = mean(Data(first:last, 2))
end