Loop index variable scope
Mostrar comentarios más antiguos
I was writing a code in MATLAB and it was something wrong in my output. I spent a lot of time checking each and every thing from the start because MATLAB was not indicating any error in the script. After spending 30 minutes i found that i was using a loop index variabe that was for another loop. Like in the second loop I was mistakenly using i instead of k so instead of giving any error or any warning indication it just used the last value of i=3
Isn't it supposed to give error or warning that variable i is not defined in loop 2 or globally as it is locally defined in loop 1.
for i = 1:3
disp(i)
end
for k = 1:2
disp(i)
end
2 comentarios
Robert Laws
el 4 de Nov. de 2021
It has long annoyed me that there is no option to turn on loop-scoped indexes.
I am in the habit adding a 'clear x' after each loop end, but that is easy to mess up when later editing the script.
Is there really no way to achieve this?
Walter Roberson
el 4 de Nov. de 2021
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!