How do I draw and ROTATE A RECTANGLE
14 views (last 30 days)
Show older comments
Create a function to draw a rectangle at an angle and fill in the rectangle with a specified color. The function header must look like: function[] = lastname_draw_rectangle(center_location,L,H, theta, rgb) Here, center_location is a vector containing the x and y coordinates of the center of the rectangle, L is the length, H is the height, theta is the rotation of the rectangle about its center in degrees, and rgb is a 3-entry vector with the rgb color we wish to use in filling the rectangle. Here is how you find the coordinates of a rotated rectangle. The unrotated xy coordinates are given by -L/2 L/2 L/2 -L/2 XY= -H/2 -H/2 H/2 H/2
then we rotate the rectangle about its center to create new coordinates;
cos(theta) -sin(theta)
R= [ ]
sin(theta) cos(theta)
T= R*(XY)
You obtain the final x vector by adding center_location(1) (the x center)to the first row of T. You obtain the final y vector by adding center_location(2) (the y center to the second row of T. fill the rectangle with the rgb color.
to check the function the use draw_rectangle([0,0],2,1,135,[1 0 0]) this should be a red rectangle at an angle of 135 degrees.
0 Comments
Answers (3)
Rik
on 1 Feb 2018
If you have any trouble with this solution, show you put in some effort to solve your own homework. This is a forum where you can get help, not find people to do your work for you.
0 Comments
need help
on 1 Feb 2018
2 Comments
Rik
on 1 Feb 2018
You're close. (Also, you posted this in the answer field, not the comment field)
You forgot to check if the cos and sin functions take degrees or radians as input (it's the latter, so you need to convert them).
The second thing is that fill doesn't accept RGB triplets as input (but patch does).
Y Yoon
on 26 Sep 2019
Edited: Y Yoon
on 26 Sep 2019
I think the coordinate has problem to draw rectangle. It needs revision for the coordination, I just see triangle, not rectangle.
revision
%---------------
function[]= draw_rectangle(center_location,L,H,deg,rgb)
theta=deg*pi/180;
center1=center_location(1);
center2=center_location(2);
R= ([cos(theta), -sin(theta); sin(theta), cos(theta)]);
X=([-L/2, L/2, L/2, -L/2]);
Y=([-H/2, -H/2, H/2, H/2]);
for i=1:4
T(:,i)=R*[X(i); Y(i)];
end
x_lower_left=center1+T(1,1);
x_lower_right=center1+T(1,2);
x_upper_right=center1+T(1,3);
x_upper_left=center1+T(1,4);
y_lower_left=center2+T(2,1);
y_lower_right=center2+T(2,2);
y_upper_right=center2+T(2,3);
y_upper_left=center2+T(2,4);
x_coor=[x_lower_left x_lower_right x_upper_right x_upper_left];
y_coor=[y_lower_left y_lower_right y_upper_right y_upper_left];
patch('Vertices',[x_coor; y_coor]','Faces',[1 2 3 4],'Edgecolor',rgb,'Facecolor','none','Linewidth',1.2);
axis equal;
end
See Also
Categories
Find more on Logical 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!