필터 지우기
필터 지우기

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