フィルターのクリア

Changing code into a loop

1 回表示 (過去 30 日間)
James Connor
James Connor 2015 年 10 月 18 日
編集済み: Geoff Hayes 2015 年 10 月 22 日
James' question was concerned with how you might go about repeating the same block of code
t.push()
t.turn(turnAngle);
t.up();
t.go(1);
t.down();
t.push();
t.turn(-9*pi/10)
t.go(sin(pi/5)/sin(7*pi/10))
t.pop();
t.turn(9*pi/10);
t.down();
t.go(sin(pi/5)/sin(7*pi/10));
t.pop();
% increment the turn angle
five time with the only difference being the turnAngle.

回答 (1 件)

Geoff Hayes
Geoff Hayes 2015 年 10 月 18 日
編集済み: Geoff Hayes 2015 年 10 月 18 日
James - just use a local variable to store the turn angle, and update it on each iteration of the for loop. Try something like the following
t=Turtle();
turnAngle = pi/2;
for k=1:5
t.push()
t.turn(turnAngle);
t.up();
t.go(1);
t.down();
t.push();
t.turn(-9*pi/10)
t.go(sin(pi/5)/sin(7*pi/10))
t.pop();
t.turn(9*pi/10);
t.down();
t.go(sin(pi/5)/sin(7*pi/10));
t.pop();
% increment the turn angle
turnAngle = turnAngle + 2*pi/5;
end
  2 件のコメント
James Connor
James Connor 2015 年 10 月 18 日
Thanks a lot. By the way what does the k=1:5 do? Is it because it's a 5 pointed star? would I changed this to k=n for a star that has n points?
Geoff Hayes
Geoff Hayes 2015 年 10 月 18 日
James - see for loop for details on the usage of a for loop. Since you have five blocks of repeating code, then k=1:5 just executes the block of code five times, setting the indexing variable k to 1, 2, 3, 4, and 5 on each iteration of the loop. Try using the MATLAB debugger and step through the code to see what is happening.

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

カテゴリ

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