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 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