Using a variable which is defined in a loop inside a nested function
12 views (last 30 days)
Show older comments
hi.
I have this code:
for i = 1:5
if A(i) == 1
.........
end
end
and I get this error: " Outer loop index 'i' is set inside a nested function "
which is not really important, because it works fine. but I want to know where the problem is.
Thanks for any help.
3 Comments
Geoff Hayes
on 7 Jun 2022
Edited: Geoff Hayes
on 7 Jun 2022
for i = 1:100
fprintf('i = %d\n', i);
i = 2; % not a good idea
end
exhibits the warning "Loop index i is changed inside a FOR loop" at line i=2;. This is similar to your warning (not an error) so perhaps you are doing something like this in the code that you haven't posted. While this doesn't seem to cause a problem with the results it is misleading and would probably cause problems in other programming languages. As such, it should be addressed.
Jan
on 7 Jun 2022
Your code snippet does not contain a nested function. Please post some code, which show this warning (this is not an error). Without seeing the relevant part of the code, it is hard to guess, where the problem is.
Answers (1)
Pooja Kumari
on 10 Jun 2022
Edited: Pooja Kumari
on 12 Jun 2022
Dear Mahdi,
I am Pooja Kumari and it is my understanding that you are facing ‘Outer loop index 'i' is set inside a nested function’ warning while running the above code.
This warning occurs when the index value of the indicated ‘for’ loop changes inside the loop body.
This happen when loops nest and an inner loop reuses the name of an outer loop index.
A = ones(1,5);
% for loop with index variable named 'i'
for i = 1:5
if A(i) == 1
i = i+1; % index 'i' is reused in nested loop
end
disp(i); %shows index 'i' will not be updated by nested loop
end
MATLAB ignores any changes that took place within a nested loop and MATLAB resets the loop index to the next value of outer loop when it returns from nested loop.
From the above example, you can see that the value of i is updating as 1,2,3,4,5.
It is advised that you can change the name of one of the for-loop indexes to avoid this warning. And if you want to keep this, then you can add a comment in your documentation and you can supress the message from the “Adjust Code Analyzer Message Indicators and Messages” which is provided in the link below:
https://in.mathworks.com/help/matlab/matlab_prog/check-code-for-errors-and-warnings.html#brqxeeu-167
Sincerely,
Pooja Kumari
1 Comment
Jan
on 10 Jun 2022
The error message posted by the OP contains the keyword "nested function". Your code example does neither contain a nested function nor a nested loop.
See Also
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!