Changing code into a loop
1 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
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 个评论
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 Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!