How to "keep" a variable for some rows within a for loop

1 visualización (últimos 30 días)
buhmatlab
buhmatlab el 22 de Abr. de 2020
Comentada: Ameer Hamza el 22 de Abr. de 2020
Hi,
My problem is the following:
I've created a for-loop in which I calculate SOMETHING(i) for each row (see code below). But I'm not able to keep the variable "SOMETHING" for some rows since i updates this variable in each row.
My goal is not to use the current variable SOMETHING of (i) in each row, I rather wanna calculate c with the same "SOMETHING" for 10 rows.
For example:
In the first 10 rows I would like to use SOMETHING(1) for my calculation of variable c and in row 11 I would like to use
SOMETHING(11) = SOMETHING(1) + c(1) + c(2) + c(3) + c(4) + c(5) + c(6) + c(7) +c(8) + c(9) + c(10)
With SOMETHING(11) I would like to calculate c for the next 10 rows again and so on...
Is there a way to achieve this?
Would I need to use another for loop?
MANY THANKS!!!
WRONG CODE:
for i = length(a)
c(i) = a(i) + b(i) * SOMEHING(i)
SOMETHING(i) = c(i) + SOMETHING(i)
end

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 22 de Abr. de 2020
Editada: Ameer Hamza el 22 de Abr. de 2020
Try something like this
for i = 1:length(a)
idx = floor((i-1)/10)*10 + 1;
c(i) = a(i) + b(i) * SOMEHING(idx);
if mod(i,10)==1
SOMETHING(idx) = c(idx-9:idx) + SOMETHING(idx);
end
end
  8 comentarios
buhmatlab
buhmatlab el 22 de Abr. de 2020
Oops! Unfortunately I was out of my mind...this little tweak makes totally sense!
Thank you so much!!!
Ameer Hamza
Ameer Hamza el 22 de Abr. de 2020
I am glad to be of help.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by