Using a variable which is defined in a loop inside a nested function

16 次查看(过去 30 天)
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 个评论
Geoff Hayes
Geoff Hayes 2022-6-7
编辑:Geoff Hayes 2022-6-7
@Mahdi Hayati - are you perhaps setting i to something else within the loop? For example,
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
Jan 2022-6-7
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.

请先登录,再进行评论。

回答(1 个)

Pooja Kumari
Pooja Kumari 2022-6-10
编辑:Pooja Kumari 2022-6-12
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:
Sincerely,
Pooja Kumari
  1 个评论
Jan
Jan 2022-6-10
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by