Is it possible to rotate a rectangle?
    7 views (last 30 days)
  
       Show older comments
    
I have,
GAL_fld = [227 360 105 65];
figure
plot(ExtractedX, ExtractedY);
rectangle ('position', GAL_fld);  %GAL
    -However how could i rotate a rectangle in this format, because I want it at an angle
0 Comments
Answers (2)
  DGM
      
      
 on 27 Jun 2025
        
      Edited: DGM
      
      
 on 27 Jun 2025
  
      The rotate() function only applies to certain types of graphics objects, and rectangle() objects are not included.  You can still use hgtransform() on rectangles though.  This answer includes an example:
In that answer, I also include code to generate XY vertex data that can be used directly with plot(), patch(), polyshape(), etc.  In that way, you can easily create rounded rectangles which mimic those created by rectangle(), but without the limitations of using rectangle objects.
0 Comments
  Vedant Shah
 on 27 Jun 2025
        To draw a rotated rectangle in MATLAB, the built-in ‘rectangle’ function is not suitable, as it only supports axis-aligned rectangles. Instead, the rectangle can be manually constructed by calculating the coordinates of its four corners after rotation and then using the ‘fill’ or ‘patch’ function to render it.
Below is a sample code snippet that demonstrates this approach: 
x = 227; y = 360; w = 105; h = 65;  
theta = 30; 
corners = [x, y; x+w, y; x+w, y+h; x, y+h]'; 
cx = x + w/2;  
cy = y + h/2; 
corners_centered = corners - [cx; cy]; 
R = [cosd(theta) -sind(theta); sind(theta) cosd(theta)]; 
rotated_corners = R * corners_centered + [cx; cy]; 
figure;  
hold on 
h = fill(rotated_corners(1,:), rotated_corners(2,:), 'r'); 
set(h, 'FaceColor', 'none', 'EdgeColor', 'r', 'LineWidth', 2); 
axis equal 
hold off 
Above code calculates the corners of a rectangle based on its position and size, then rotates it around its center using a rotation matrix. After applying the transformation, it uses the “fill” function to draw the rotated rectangle with a red border and no fill color. This approach allows for flexible visualization of rectangles at any orientation. 
For more information, refer to the following documentations: 
0 Comments
See Also
Categories
				Find more on Interactions, Camera Views, and Lighting 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!

