# rotating a 2d shape

131 views (last 30 days)
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.

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
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');
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
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.

### Categories

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!