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 CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by