Adding a different quantity to intervals of an array. Avoding looping?
Say I have an array of values:
values = 1:100;
an array of indices:
interval_indices = [40 45 80];
and an array of quantities that I would like to add to the elements in values
:
quantities_开发者_JAVA百科to_add = [5 -9 30];
I am looking for a compact expression in MATLAB (maybe using accumarray
?) that allows me to add the elmements of quantities_to_add
to the elements in values
depending on the indices specified by indices
.
If I were to do this manually:
values(1:interval_indices(1)) = values(1:interval_indices(1)) + ...
quantities_to_add(1);
values(interval_indices(1):interval_indices(2)) = values(interval_indices(1):interval_indices(2)) + ...
quantities_to_add(2);
% and so forth
values(interval_indices(end-1):interval_indices(end)) = values(interval_indices(end-1):interval_indices(end)) + ...
quantities_to_add(end);
EDIT:
Actually, this is a much smarter and vectorized way of doing the same:
lastIndx=interval_indices(end);
quantitiesVector=zeros(1,lastIndx);
quantitiesVector([1,interval_indices(1:end-1)+1])=[quantities_to_add(1) diff(quantities_to_add)];
newValues=[values(1:lastIndx)+cumsum(quantitiesVector),values(lastIndx+1:end)];
Previous answer:
One way of doing it is using arrayfun
to generate a vector of quantities and then adding.
intervalLength=diff([0 indices]);
lastIndx=interval_indices(end);
quantities=cell2mat(arrayfun(@(x)ones(1,intervalLength(x))*quantities_to_add(x),1:numel(indices),...
'UniformOutput',false));
newValues=[values(1:lastIndx)+quantities, values(lastIndx+1:end)];
精彩评论