rotating a 2d shape

131 views (last 30 days)
Shaan Ali
Shaan Ali on 23 Jul 2016
Commented: Duc Nguyen on 19 Feb 2020
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.

Accepted Answer

Geoff Hayes
Geoff Hayes on 23 Jul 2016
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
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
Duc Nguyen
Duc Nguyen on 19 Feb 2020
The vertices are not at 90 degrees angle because your axes do not have the same scale. Your unit-length of the horizontal axis in the picture is a bit longer than a unit-length of the vertical axis. If you add another command line "axis equal" then the four vertices should be at 90 degrees angle again.

Sign in to comment.

More Answers (0)


Find more on Graphics Object Programming in Help Center and File Exchange


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!