How to count each element in array

1 visualización (últimos 30 días)
Kenneth Sabandar
Kenneth Sabandar el 21 de Mzo. de 2019
Comentada: Kenneth Sabandar el 23 de Mzo. de 2019
in my case, i have an array enveloped in for loop
for i = 1:6
array = [0.5 1 5 2 7 3]
end
now i want to show the result of sum in array element (ex: 0.5 + 1 on first iteration, then 1.5(result of previous iteration) + 5 and so on)
the code that i already try is :
array(i) = array(i) + array(i-1)
but i can't get the result. i already tried with temp, but the problem persists.
thank you
  4 comentarios
Walter Roberson
Walter Roberson el 21 de Mzo. de 2019
What you had before
array(i) = array(i) + array(i-1)
should work, provided i starts at 2.
... But you need to be sure not to overwrite all of array in the loop. The assignment to array should not have been in a loop.
Kenneth Sabandar
Kenneth Sabandar el 21 de Mzo. de 2019
thank you! i really appreciate it

Iniciar sesión para comentar.

Respuesta aceptada

Krishna Kumar
Krishna Kumar el 21 de Mzo. de 2019
Are you just interested in this?
array = [0.5 1 5 2 7 3];
sum=cumsum(array)
If you just want add two neighbouring terms, this should work:
sum= array(1:end-1)+array(2:end)
which basically adds an element with previous one.
  1 comentario
Kenneth Sabandar
Kenneth Sabandar el 23 de Mzo. de 2019
thank you! solved my problem right away :)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

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

Etiquetas

Productos


Versión

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by