例如,我有5个时间步长和一个持续时间值:
TimeSteps = [4, 5, 6, 7, 8, 10, 11, 12, 14, 15, 16];
Duration = [5, 3, 3];
我想自动生成每个持续时间的时间步长之间的平均值。在这种情况下,结果将如下所示:
Result = [mean([4, 5, 6, 7, 8]), mean([10, 11, 12]), mean([14, 15, 16])];
这将导致:
Result = [6, 11, 15];
我有一个474x1的持续时间向量,所以我需要自动化这个。如果有人可以提供帮助,那就太好了。谢谢。
答案 0 :(得分:5)
您需要将mean
功能应用于TimeSteps
的大小为Duration
的分区:
Partition = mat2cell(TimeSteps, 1, Duration);
Result = cellfun(@mean, Partition)
如果你是单行的粉丝:
Result = cellfun(@mean, mat2cell(TimeSteps, 1, Duration));
注意:请注意此解决方案是针对行向量发布的;更改列向量的mat2cell
调用。
答案 1 :(得分:4)
可以使用accumarray
轻松完成。这适用于行或列向量。
ind = [];
ind(cumsum(Duration(end:-1:1))) = 1;
ind = cumsum(ind(end:-1:1)); %// generate grouping index for accumarray
Result = (accumarray(ind(:), TimeSteps(:))./Duration(:)).';
答案 2 :(得分:3)
使用 bsxfun
的屏蔽功能 -
%// Setup mask to be used to map Timesteps values onto a 2D matrix
mask = bsxfun(@ge,Duration(:).',[1:max(Duration)]') %//'
%// Initiliaze the 2D matrix where Timesteps values would be put with NaNs
vals = nan(size(mask))
%// Now, put those values
vals(mask) = TimeSteps
%// Find mean along columns for the final output
Result = nanmean(vals,1)
输出 -
Result =
6 11 15