How can I write a function that draws a regular polygon with n sides in a polar coordinate plot?
Show older comments
I am unfamiliar with plotting with polar coordinates. Here is what I have so far, which does not work:
function polygon(sides) % Name number of sides of the polygon
degrees=360/sides; % Find the angle between corners in degrees
radius=ones(1,sides) % Array of ones
theta=0:degrees:360 % Theta changes by the internal angle of the polygon
polar(theta, radius) % Plot
end
Thanks!
1 Comment
Danielle Wojeski
on 31 Dec 2016
Edited: Walter Roberson
on 31 Dec 2016
%First you need to define the sides variable.
sides=input('input the number of sides you want;, ')
Then you need to make sure the radius and the theta match in size. If your theta starts at 0 it will always be one size bigger then your radius. So instead make it a 1.
It should look like this...
function polygon(sides) % Name number of sides of the polygon
sides = input('input the number of sides you want;, ');
degrees = 360./sides; % Find the angle between corners in degrees
r = ones(1,sides) % Array of ones
theta = 1:degrees:360 % Theta changes by the internal angle of the polygon
polar(theta, r) % Plot
end
Accepted Answer
More Answers (1)
Carson Cooper
on 13 Feb 2017
Edited: Carson Cooper
on 13 Feb 2017
0 votes
This gives a better output than those above
function polygon(sides)
sides = input('input the number of sides you want;, ');
radians = (2*pi)./sides;
r = ones(1, sides);
theta = 1:radians:2*pi;
polar(theta, r)
end
4 Comments
Gigglemello
on 1 Mar 2017
Thank you for this! But, why did I get an open-ended polygon? How do I close it?
Sophie
on 3 Mar 2017
sides = input('input the number of sides you want;, ');
radians = (2*pi)./sides;
r = ones(1, sides+1);
theta = 0:radians:2*pi;
polar(theta, r)
This seemed to fix the openness of the polygon. I don't understand why tho :3
Anders Bray
on 11 Jul 2022
theta includes 0 as the first step making it an 1x(sides+1) that is why have to accomidate.
debashish panda
on 29 Aug 2022
for n=3:1:6
subplot(2,2,n-2)
polygon(n)
end
function polygon(sides)
radians = (2*pi)./sides;
r = ones(1, sides+1);
theta = 0:radians:2*pi;
polar(theta, r)
end
Categories
Find more on Grid Lines, Tick Values, and Labels in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!