MATLAB: Rotating a 2d shape

2d objectMATLABrotate

Hello, I am new to matlab and I was having trouble understanding how to rotate a 2d object (shape) counter clockwise using sin and cos? Please let me know if there is anything you can do to help.

Best Answer

Shaan - see rotation matrix which you can construct to rotate your (x,y) points (of your 2D shape) so that you can rotate them counter-clockwise.
For example, if you know the four vertices of the square that you wish to draw, then you can use the MATLAB fill function to create it
X = [-2 -2 2 2];
Y = [-2 2 2 -2];
hSquare = fill(X,Y,'k');
where X and Y are the x and y coordinates of the vertices, and hSquare is the handle to the square (polygon) that you have drawn.
Suppose you now want to rotate the square by one degree in a counter-clockwise direction. The rotation matrix is the usual
thetad = 1;
R = [cosd(thetad) -sind(thetad); sind(thetad) cosd(thetad)];
We can get the vertices from the drawn square since we have its handle
V = get(hSquare,'Vertices')';
We could multiply V by R to get the rotated set of vertices, but this would only be valid if the centre of the square is (0,0). As that will not always be the case, then you will need to translate the square from its current coordinate system to one centred at (0,0). We can do this and the rotation as follows
V = R*(V - C) + C;
where C is an appropriately sized matrix with the centre of the square (use repmat to create this C given the (x,y) coordinates for the centre). So we translate to the coordinate system centred at (0,0) (the subtraction), rotate (the multiplication), and then translate back to the original coordinate system whose origin is the centre of the square (the addition). We can then update the square with the new vertices as
set(hSquare,'Vertices',V');
and the rotation by one degree is complete. Putting this all together to rotate the square over 360 degrees, we would do
X = [-2 -2 2 2];
Y = [-2 2 2 -2];
hSquare = fill(X,Y,'k');
thetad = 1;
R = [cosd(thetad) -sind(thetad); sind(thetad) cosd(thetad)];
C = repmat([0 0], 4, 1)';
axis([-10 10 -10 10])
for k=1:360
V = get(hSquare,'Vertices')'; % get the current set of vertices
V = R*(V - C) + C; % do the rotation relative to the centre of the square
set(hSquare,'Vertices',V'); % update the vertices
pause(0.01);
end