Adding values in an array within limits

1 visualización (últimos 30 días)
Nikolas Spiliopoulos
Nikolas Spiliopoulos el 29 de Mzo. de 2017
Editada: Stephen23 el 29 de Mzo. de 2017
Hi all,
I have a vector A=[1 2 3 4 5 4]'
I would like to get from vector A, a vector B where its elements are the same with A, until the cumulative sum becomes 9. When the limit of 9 is reached the rest of the elements will be zero.
So the vector B will be : B=[1 2 3 3 0 0]'
I don't know if I explained it well
thanks in advance
Nikolas

Respuesta aceptada

Adam
Adam el 29 de Mzo. de 2017
Editada: Adam el 29 de Mzo. de 2017
B = zeros( size( A ) );
validIdx = cumsum( A ) <= 9;
B( validIdx ) = A( validIdx );
B( nnz( validIdx ) + 1 ) = 9 - sum( B );
would work, assuming you just clip the final value so you have a sum of 9.

Más respuestas (1)

Stephen23
Stephen23 el 29 de Mzo. de 2017
>> A = [1;2;3;3;5;4];
>> B = A.*(cumsum(A)<=9)
B =
1
2
3
3
0
0
  2 comentarios
Nikolas Spiliopoulos
Nikolas Spiliopoulos el 29 de Mzo. de 2017
Basically my vector is A = [1;2;3;4;5;4]; not A = [1;2;3;3;5;4];
thanks!
Stephen23
Stephen23 el 29 de Mzo. de 2017
Editada: Stephen23 el 29 de Mzo. de 2017
@Nikolas Spiliopoulos: you can use whatever vector you want.
I just used the vector that fitted your desired output, which you gave as "B=[1 2 3 3 0 0]'". Did I guess wrong? If you could please explain the reason for why the fourth elements of A and B should be different, then I can show you how to achieve what you want.

Iniciar sesión para comentar.

Categorías

Más información sobre Elementary Math en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by