changing the running variable in a "for" loop

5 visualizaciones (últimos 30 días)
Pultibus
Pultibus el 11 de Ag. de 2017
Comentada: Star Strider el 12 de Ag. de 2017
I want that the running variable of my for loop changes in the loop. But when I take the next step in the for loop, my made changes for n disappear. In some tutorials was written that I have to use a while loop. But this isn't working as well. Is there an other possibility to solve my problem?
for n = 1:size(t,2)
dv = v_0(n+1) - v_0(n);
while dv ~= 0
while dv > 0
...
n = n + dt/delta_t+1;
break
end
while dv < 0
...
break
end
break
end
...
continue
end

Respuestas (3)

Star Strider
Star Strider el 11 de Ag. de 2017
You cannot change the loop index variable within a for loop:
n = n + dt/delta_t+1;
Since ‘n’ is going to increment anyway, avoid confusion and name the assigned variable something else:
nv = n + dt/delta_t+1;
then use it for your calculations.

Chad Greene
Chad Greene el 11 de Ag. de 2017
Yes, I see the problem. It does not make sense to have the for loop variable be the same name as a variable you're defining within the for loop. Perhaps you want something like
n2 = 0;
for n = 1:size(t,2)
...
n2 = n2 + dt/delta_t+1;
end
Or in some way separate n from n2.

Pultibus
Pultibus el 12 de Ag. de 2017
Thank you for your answers! Sadly your hints couldn't help me. I did it in another way and my program works now.
Greetings
Pultibus

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