sum of variable-size subvectors of array without loops

1 次查看(过去 30 天)
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,:);

采纳的回答

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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB Coder 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by