필터 지우기
필터 지우기

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

조회 수: 12 (최근 30일)
Mahdi Hayati
Mahdi Hayati 2022년 6월 7일
편집: Pooja Kumari 2022년 6월 12일
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