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?
-
1You 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.Hoki– Hoki2020-11-11 17:45:43 +00:00Commented Nov 11, 2020 at 17:45
1 Answer
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 2π radians (0° 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.
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
