How can I do cumulative sum separately in one array?

3 vues (au cours des 30 derniers jours)
Hengfeng Wang
Hengfeng Wang le 20 Juin 2015
Commenté : the cyclist le 20 Juin 2015
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.

Réponses (3)

Image Analyst
Image Analyst le 20 Juin 2015
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 commentaires
the cyclist
the cyclist le 20 Juin 2015
You'll want to preallocate B if A is long. Put
B = zeros(size(A));
ahead of the algorithm.
the cyclist
the cyclist le 20 Juin 2015
In limited testing, this simple solution is fastest, by a large margin (assuming you put in the preallocation).

Connectez-vous pour commenter.


Guillaume
Guillaume le 20 Juin 2015
Modifié(e) : Guillaume le 20 Juin 2015
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 le 20 Juin 2015
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);

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by