sum of variable-size subvectors of array without loops
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Dave Lee
il 13 Nov 2018
Modificato: Dave Lee
il 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,:);
0 Commenti
Risposta accettata
Walter Roberson
il 13 Nov 2018
cumsum . Then the problem reduces to a linear difference of positions .
0 Commenti
Più risposte (0)
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!