Using while loop in a function?

3 views (last 30 days)
Jenniluyn Nguyen
Jenniluyn Nguyen on 10 Mar 2020
Answered: David Hill on 10 Mar 2020
Hello! First of all thank you for helping me out, this forum has done a lot to teach me more about MatLab.
I have a function that rotates a shape on a plot by however many degrees is inputted, which looks like this:
function [newx newy] = rotate(xcoords, ycoords, angle)
angle = angle*(pi/180); % convert angle to radians
newx = xcoords*cos(angle) - ycoords*sin(angle);
newy = xcoords*sin(angle) + ycoords*cos(angle);
I'm trying to write a second function with this function (we'll call rotate) with a while loop, but it does not seem to be working. What I want to do is when there is an input of x coordinates, y coordinates, and a number (which I assigned to repeats), it plots the specified number of rotations on a graph.
function [xc1, xc2] = spin(xcoords1, ycoords1,repeats)
degreeangle = 360/repeats;
hold on
while repeats > 1
[xc1, xc2] = rotate(xcoords1,ycoords1,degreeangle);
plot(xcoords1,ycoords1,'b-')
end
hold off
I am not sure why my code isn't working. Would appreciate any help! Thank you!

Accepted Answer

David Hill
David Hill on 10 Mar 2020
function spin(xcoords1, ycoords1,repeats)
degreeangle = 360/repeats;
hold on
while repeats > 1
[xcoords1, ycoords1] = rotate(xcoords1,ycoords1,degreeangle);
plot(xcoords1,ycoords1,'b-')
repeats=repeats-1;
end
hold off

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!