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

30 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by