MATLAB: Sum of variable-size subvectors of array without loops

forfor loopsubvectorvariable sizevectorization

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,:);

Best Answer

cumsum . Then the problem reduces to a linear difference of positions .