フィルターのクリア

sum of variable-size subvectors of array without loops

4 ビュー (過去 30 日間)
Dave Lee
Dave Lee 2018 年 11 月 13 日
編集済み: Dave Lee 2018 年 11 月 13 日
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 Center および File ExchangeNumeric Types についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by