How to transform a wile loop into a for loop

7 ビュー (過去 30 日間)
Danny Maefengea
Danny Maefengea 2020 年 6 月 18 日
コメント済み: Danny Maefengea 2020 年 6 月 18 日
Hi
I have been working with while and for loops, and I want to know how to transpose or change a while loop to a for loop and vise versa
I need your help with this.
Thank you
  2 件のコメント
James Tursa
James Tursa 2020 年 6 月 18 日
What have you tried so far? What problems are you having with this homework assignment?
Danny Maefengea
Danny Maefengea 2020 年 6 月 18 日
編集済み: madhan ravi 2020 年 6 月 18 日
This is what I have done sir.
%while loop
x=0
while x<20
disp(x);
x = x+2;
end
%%for loop
x = 0
for x=0;x<20;x=x+2
disp(x)
end

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

採用された回答

Pulkit Goel
Pulkit Goel 2020 年 6 月 18 日
In MATLAB, fo create a for loop, instead of specifying x=x+2 like you do in C, you write the skip as 0:2:20. This would make your code look like:
x=0;
for x=0:2:20
disp(x);
end
For creating while loop, it is similar to what you mentioned, as we have in C:
x=0;
while x<=20
disp(x);
x=x+2;
end
The equality sign is required in while as the condition is evaluated at start and logic will fail to enter the loop when you have updated the value of x to 20, but are yet to print it.

その他の回答 (1 件)

Anish Walia
Anish Walia 2020 年 6 月 18 日
The for loop for your while loop would be
% 0:2:20 will produce a matrix starting at 0, with increment step of 2 in each iteration and will go till 20
for x=0:2:20
disp(x);
end
For more information on loops refer to the following:

カテゴリ

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