0

I want to create a function in matlab which plots a polygon based on number of sides of the polygon which should be the input of the function.How can I generate this code?

1
  • 1
    You need an equation or a formulation which will be able to describe each type of polygon you want to create. When you have that, you can start translating it into code. When you have a code started, you can ask here again for help if it does not work. Commented Nov 11, 2020 at 17:45

1 Answer 1

1

Generating Polygons from Sampling a Circle

You can take sample points along a circle and join them, but of course, depending on the criteria for the generated polygons this may or may not suit your requirements. In this case, you'll need the number of points to be 1 greater than the number of edges to close the shape. Here we denote a vector Theta which takes evenly spaced sample angles from 0 to radians ( to 360°). These sample angles stored in Theta are then used to calculate xy-points along a circle by using sin() and cos() relationships. The last step is to multiply by the Radius since sin() and cos() of an angle are normalized to the unit circle.

Polygon Plot with Specified Number of Edges

Number_Of_Edges = 6;

Radius = 100;
Theta = linspace(0,2*pi,Number_Of_Edges+1);
X_Points = Radius*cos(Theta);
Y_Points = Radius*sin(Theta);

plot(X_Points,Y_Points);
title("Polygon with " + num2str(Number_Of_Edges) + " Edges");
grid;

Function Call:

Number_Of_Edges = 6;
Polygon_Plot(Number_Of_Edges);

Function Form:

function [] = Polygon_Plot(Number_Of_Edges)
Radius = 100;
Theta = linspace(0,2*pi,Number_Of_Edges+1);
X_Points = Radius*cos(Theta);
Y_Points = Radius*sin(Theta);


plot(X_Points,Y_Points);
title("Polygon with " + num2str(Number_Of_Edges) + " Edges");
grid;

end

Ran using MATLAB R2019b

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.