MATLAB: How to plot an orientated rectangle having coordinates and angle

MATLABorientateorientationplotquiverrectanglerotatetranslate

Hello everybody,
I have a simple problem that I cannot manage to solve in Matlab.
I am representing the behavior of a vehicle traveling on a given car track and I would like to plot orientated rectangles instead of the standard markers present in the plot environment. I am able to reproduce the orientation through the quiver function, but I am not able to use rectangles instead of the arrows.
Note that I would like to have a rectangle for every instant k (i.e.: if I have 10 instants, ten different rectangles for every position).
This is the code I use for the moment with quiver:
scale_factor = 10;
r = 1; % magnitude (length) of arrow to plot
x = x_c; y = y_c;
angle = alpha+beta;
u = r * cos(angle); % convert polar (theta,r) to cartesian
v = r * sin(angle);
h = quiver(x,y,u*scale_factor,v*scale_factor,'--','LineWidth',3,'AutoScale','off');
I have also tried this one translating manually each point but it does not work:
function[]= draw_rectangle1(x_c,y_c,theta)
L = 20;
H = 10;
x_low_left = x_c - L/2;
x_low_right = x_c + L/2;
x_up_right = x_c + L/2;
x_up_left = x_c - L/2;
y_low_left = y_c - H/2;
y_low_right = y_c - H/2;
y_up_right = y_c + H/2;
y_up_left = y_c + H/2;
x_low_left_new = cos(theta)*(x_low_left-x_c)-sin(theta)*(y_low_left-x_c)+x_c;
y_low_left_new = sin(theta)*(x_low_left-x_c)+cos(theta)*(y_low_left-x_c)+y_c;
x_low_right_new = cos(theta)*(x_low_right-x_c)-sin(theta)*(y_low_right-x_c)+x_c;
y_low_right_new = sin(theta)*(x_low_right-x_c)+cos(theta)*(y_low_right-x_c)+y_c;
x_up_right_new = cos(theta)*(x_up_right-x_c)-sin(theta)*(y_up_right-x_c)+x_c;
y_up_right_new = sin(theta)*(x_up_right-x_c)+cos(theta)*(y_up_right-x_c)+y_c;
x_up_left_new = cos(theta)*(x_up_left-x_c)-sin(theta)*(y_up_left-x_c)+x_c;
y_up_left_new = sin(theta)*(x_up_left-x_c)+cos(theta)*(y_up_left-x_c)+y_c;
x_coor=[x_low_left_new x_low_right_new x_up_right_new x_up_left_new];
y_coor=[y_low_left_new y_low_right_new y_up_right_new y_up_left_new];
fill(x_coor, y_coor,'r');
end
I have also given a chance to patch but no way.
If anyone can help me with this simple but tricky code it would be awesome.
Thank you!

Best Answer

You have to perform the rotation in an object-centered coordinate frame.
Define the rectangle:
X = [-L/2 L/2 L/2 -L/2];
Y = [-H/2 -H/2 H/2 H/2];
Now perform the rotation in the object-centered frame:
theta = % The rotation angle
cth = cos(theta) ;
sth = sin(theta);
Xrot = X*cth + Y*sth;
Yrot = -X*sth + Y*cth;
Now when you generate the graphic, add the true position:
fill(Xrot + Xc, Yrot + Yc,'r')
Related Question