Sum of an array elements with condition on the sum value

2 visualizaciones (últimos 30 días)
Moammer Elzwail
Moammer Elzwail el 30 de Nov. de 2019
Editada: dpb el 30 de Nov. de 2019
Hi everybody,
I would like some help here.
So I have a vector (C) that has 10 random numbers.
C = [ 2 5 4 3 6 7 3 4 2 1]. I would like to cumulatively sum the elements with the condition of the sums not exceeding 12 i.e 2+5+4 = 11 (under 12) then move to the next 3+6 = 9 (under 12) .. ans so on. Then storing the cumulaitve sums in a differnt vector G. So the results will be like: G = [11 9 10 7].
Thank you
  1 comentario
dpb
dpb el 30 de Nov. de 2019
Editada: dpb el 30 de Nov. de 2019
Probably just the straightforward loop is the simplest here...
You could use cumsum and locate the position via find(cumsum(C)<12,1,'last') and then repeat again with the subsequent portion of the original vector, but I suspect just the straightahead sum will be quicker to code and probably faster.
No really unique solution pops to mind....not to say there isn't one.

Iniciar sesión para comentar.

Respuestas (0)

Categorías

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

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by