How can I do cumulative sum separately in one array?

3 visualizaciones (últimos 30 días)
Hengfeng Wang
Hengfeng Wang el 20 de Jun. de 2015
Comentada: the cyclist el 20 de Jun. de 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.

Respuestas (3)

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

Iniciar sesión para comentar.


Guillaume
Guillaume el 20 de Jun. de 2015
Editada: Guillaume el 20 de Jun. de 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 el 20 de Jun. de 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);

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by