Effacer les filtres
Effacer les filtres

Changing code into a loop

1 vue (au cours des 30 derniers jours)
James Connor
James Connor le 18 Oct 2015
Modifié(e) : Geoff Hayes le 22 Oct 2015
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.

Réponses (1)

Geoff Hayes
Geoff Hayes le 18 Oct 2015
Modifié(e) : Geoff Hayes le 18 Oct 2015
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 commentaires
James Connor
James Connor le 18 Oct 2015
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 le 18 Oct 2015
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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by