rotate a 2d polygon around a given roation point in matlab

To rotate a 2D polygon around a given rotation point (also called pivot point), you can use the following Matlab code:

main.m
% Define the polygon vertices (in this example, a triangle)
poly = [0, 0; 4, 0; 2, 3];
% Define the rotation angle (in degrees)
theta = 30;
% Define the rotation point
pivot = [2, 2];

% Translate the polygon so that the pivot is at the origin
t1 = -pivot;
poly = bsxfun(@plus, poly, t1);

% Create the rotation matrix
R = [cosd(theta), -sind(theta); sind(theta), cosd(theta)];

% Rotate the polygon vertices
poly = poly * R;

% Translate the polygon back to its original position
t2 = pivot;
poly = bsxfun(@plus, poly, t2);
525 chars
21 lines

In this code, we first define the polygon vertices using a 2D array, where each row corresponds to a vertex. We then define the rotation angle (theta) in degrees and the rotation point (pivot) as a 2-element array.

To perform the rotation, we first translate the polygon vertices so that the rotation point is at the origin. We can do this by subtracting the pivot coordinates from each vertex using the bsxfun function.

Next, we create a 2x2 rotation matrix R using the cosd and sind functions to compute the sine and cosine of the rotation angle.

We then rotate the polygon vertices using matrix multiplication. Since the poly array has dimensions nx2 and the rotation matrix R has dimensions 2x2, we can simply multiply them using the * operator.

Finally, we translate the polygon vertices back to their original position by adding the pivot coordinates to each vertex using bsxfun. The resulting poly array contains the rotated polygon vertices.

gistlibby LogSnag