Reputation: 909
For example, I have 5 time steps and a duration value:
TimeSteps = [4, 5, 6, 7, 8, 10, 11, 12, 14, 15, 16];
Duration = [5, 3, 3];
I want to automatically generate the means between the time steps for every duration. In this case, the result would look like this:
Result = [mean([4, 5, 6, 7, 8]), mean([10, 11, 12]), mean([14, 15, 16])];
This will lead to:
Result = [6, 11, 15];
I have a 474x1 duration vector, so I need to automatize this. If anyone can help, it would be great. Thank you.
Upvotes: 4
Views: 149
Reputation: 221644
Using bsxfun
's masking capability -
%// 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)
Output -
Result =
6 11 15
Upvotes: 3
Reputation: 112749
It can be done easily with accumarray
. This works for row or column vectors.
ind = [];
ind(cumsum(Duration(end:-1:1))) = 1;
ind = cumsum(ind(end:-1:1)); %// generate grouping index for accumarray
Result = (accumarray(ind(:), TimeSteps(:))./Duration(:)).';
Upvotes: 4
Reputation:
You need to apply the mean
function to a partition of your TimeSteps
that has the sizes in Duration
:
Partition = mat2cell(TimeSteps, 1, Duration);
Result = cellfun(@mean, Partition)
If you're a fan of one-liners:
Result = cellfun(@mean, mat2cell(TimeSteps, 1, Duration));
Note: Please take in account that this solution is posted for row vectors; change the mat2cell
call for column vectors.
Upvotes: 5