Compute cumulative sum of a column vector without for loop

5 ビュー (過去 30 日間)
Aurelien Queffurust
Aurelien Queffurust 2012 年 3 月 30 日
For each index of a column vector , I want to compute the sum from index to index+spacing. spacing is an integer.
My aim is not to use for-loop but I didn't manage to find a way to avoid it:
A=(1:10)'; % column vector
spacing = 4; % scalar
solution = zeros(length(A)-spacing,1);
for index=1:length(A)-win % equals 6 in this example
solution(index)=sum(A(index:index+spacing));
end
solution =
15
20
25
30
35
40
Thanks for your help!
Aurélien

採用された回答

the cyclist
the cyclist 2012 年 3 月 30 日
The filter() command is one way:
tmp = filter(ones(1,spacing+1),1,A);
solution = tmp(spacing+1:end)

その他の回答 (1 件)

C.J. Harris
C.J. Harris 2012 年 3 月 30 日
A=(1:10)'; % column vector
spacing = 4; % scalar
solution = arrayfun(@(n) sum(A(n):A(n+spacing)), 1:length(A)-spacing)';

カテゴリ

Help Center および File ExchangeMatched Filter and Ambiguity Function についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by