Effacer les filtres
Effacer les filtres

sum of variable-size subvectors of array without loops

4 vues (au cours des 30 derniers jours)
Dave Lee
Dave Lee le 13 Nov 2018
Modifié(e) : Dave Lee le 13 Nov 2018
Hi,
I am trying to implement the code below without for loop. The idea is to calculate sum of different ranges/sizes of an array in row dimension. The calculation is applied for all columns. Note that the sizes of the extracted element vectors are reflected in index_stop-index_start, which is not a constant vector. I am looking for a general solution because this is a simplified code of a large matrix operation and the values here, such as vectors index_start, index_stop are general in the original code.
Thanks,
clear all;
x = [1,3,4,5;5,6,7,2;3,4,6,4];
index_start = [1;1];
index_stop = [2;3];
for m=1:numel(index_start)
s(m,:) = sum(x(index_start(m):index_stop(m),:));
end
%% Thanks to Walter Roberson, I put the code based on his answer here
cumsum_x = cumsum(x);
s_no_loop_method = cumsum_x(index_stop,:)-cumsum_x(index_start,:)+x(index_start,:);

Réponse acceptée

Walter Roberson
Walter Roberson le 13 Nov 2018
cumsum . Then the problem reduces to a linear difference of positions .

Plus de réponses (0)

Catégories

En savoir plus sur Numeric Types dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by