How do I draw and ROTATE A RECTANGLE
57 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(3 个)
Rik
2018-2-1
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 个评论
need help
2018-2-1
2 个评论
Rik
2018-2-1
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
2019-9-26
编辑:Y Yoon
2019-9-26
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Surface and Mesh Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!