Loop index variable scope
Show older comments
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 Comments
Robert Laws
on 4 Nov 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
on 4 Nov 2021
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!