How can I do cumulative sum separately in one array?

3 次查看(过去 30 天)
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