How can I do cumulative sum separately in one array?

3 ビュー (過去 30 日間)
Hengfeng Wang
Hengfeng Wang 2015 年 6 月 20 日
コメント済み: the cyclist 2015 年 6 月 20 日
For example, there is an array
A=[1 2 0 3 4 0 5 6 7 0 8 9]
Every time there is an zero in A, i.e. restart signal, I want the cumulative sum reset as 0 and restart the sum. The result I want from A is array
B=[1 3 0 3 7 0 5 11 18 0 8 17]
Please help me :) Cheers.

回答 (3 件)

Image Analyst
Image Analyst 2015 年 6 月 20 日
Did you think of using a simple, intuitive, and fast for loop:
A=[1 2 0 3 4 0 5 6 7 0 8 9]
theSum = 0;
for k = 1 : length(A)
if A(k) == 0
theSum = 0;
end
theSum = theSum + A(k);
B(k) = theSum;
end
% Show in command window
B
  2 件のコメント
the cyclist
the cyclist 2015 年 6 月 20 日
You'll want to preallocate B if A is long. Put
B = zeros(size(A));
ahead of the algorithm.
the cyclist
the cyclist 2015 年 6 月 20 日
In limited testing, this simple solution is fastest, by a large margin (assuming you put in the preallocation).

サインインしてコメントする。


Guillaume
Guillaume 2015 年 6 月 20 日
編集済み: Guillaume 2015 年 6 月 20 日
A = [1 2 0 3 4 0 5 6 7 0 8 9];
subarraylengths = diff([0 find(~A)-1 numel(A)]);
subarrays = mat2cell(A, 1, subarraylengths);
cumsubarrays = cellfun(@cumsum, subarrays, 'UniformOutput', false);
B = [cumsubarrays{:}]
or use a loop

the cyclist
the cyclist 2015 年 6 月 20 日
Here's another algorithm. The best one might depend on the size of A.
A = [1 2 0 3 4 0 5 6 7 0 8 9];
% Append start and end zeros temporarily
B = [0 A 0];
% Find the zeros (including "artificial" zeros tagged at the end).
zeroLocations = find(B==0);
numberZeros = numel(zeroLocations);
for ii = 1:numberZeros-1
segmentIndex = zeroLocations(ii)+1:zeroLocations(ii+1)-1;
B(segmentIndex) = cumsum(B(segmentIndex));
end
% Remove the temporary zeros
B = B(2:end-1);

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by