フィルターのクリア

"while" loop nested within "for" loop

53 ビュー (過去 30 日間)
Kevin Lai
Kevin Lai 2015 年 10 月 5 日
回答済み: Manish Kumar 2020 年 6 月 26 日
I'm terribly sorry if this seems like a very basic question (i'm just beginning to learn MATLAB). Anyways, can someone please show me a simple example of a while loop nested within a for loop? I understand the two loops separately but I can't figure out how to apply them together.

採用された回答

the cyclist
the cyclist 2015 年 10 月 5 日
N = 5;
for ii = 1:3
ii
M = ii + 1;
while M < N
M = M + 1
end
end
  1 件のコメント
Kevin Lai
Kevin Lai 2015 年 10 月 6 日
Thank you the cyclist for the answer!!! Much appreciated. If you don't mind, can you please explain to me the evaluation of M in the end (i.e. how it got M = 3, M = 4, M=5, M=4, M=5, and M=5)

サインインしてコメントする。

その他の回答 (2 件)

the cyclist
the cyclist 2015 年 10 月 6 日
You should probably read and understand the documentation of for and while.
Just follow the code step-by-step. I've commented each line to explain what it does:
N = 5; % Set N equal to 5
for ii = 1:3 % Execute the enclosed lines for ii=1, then ii=2 ,then ii=3.
ii % Display the value of ii to the screen
M = ii + 1; % Set the value of M to ii+1. Note that this is NOT displayed to the screen.
while M < N % Execute the following line until M is less than N. (Remember that N=5.)
M = M + 1 % Take the current value of M, increase it by 1, and display it to the screen.
end % Go back to the start of the while loop, and check if it is still true
end % If we have not executed the last value of the for loop index, go back to the start of the for loop and execute for the new value.

Manish Kumar
Manish Kumar 2020 年 6 月 26 日
n=10;
ans=0;
for i=1:n
j=0;
while j<i
ans=i+j;
end
end

カテゴリ

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