create a mat lab function that takes as input a number of sides and side length of polygon and outputs location of polygon vertices in matlab

The code below creates a MATLAB function that takes the number of sides n and the length of each side l as input and returns the location of the polygon vertices in a matrix vertices.

main.m
function vertices = polygon_vertices(n, l)
% Create an empty matrix for the vertices
vertices = zeros(n, 2); 

% Calculate the interior angle of the polygon
interior_angle = (n - 2) * pi / n; 

% Calculate the positions of the vertices
for i = 1:n
   vertices(i, :) = [l * cos((i-1)*2*pi/n+interior_angle), l * sin((i-1)*2*pi/n+interior_angle)];
end
end
354 chars
13 lines

To use this function in MATLAB, simply pass in the number of sides and the length of each side as arguments. For example, to create the vertices of a regular pentagon with side length 2:

main.m
>> vertices = polygon_vertices(5, 2)
vertices =
    1.1756    1.9021
    0.0000    2.0000
   -1.1756    1.9021
   -1.9021    0.5878
   -2.0000   -0.0000
153 chars
8 lines

The output vertices is a 5x2 matrix, where each row represents the x and y coordinates of a vertex.

gistlibby LogSnag