使用散点图显示具有指定方向的矩形

时间:2017-05-29 13:11:59

标签: matlab matlab-figure

我想显示一个矩形,其中心位于(x,y)位置,其长轴与x轴成角度phi。我怎么能这样做?

我可以通过

显示位置(x,y)的圆点
scatter(x,y)

但我不知道矩形。

1 个答案:

答案 0 :(得分:1)

使用fillxy坐标绘制2D多边形。

c = [0, 0];     % Position of centre
h = 5; w = 8;   % height and width of rectangle
a = deg2rad(30); % angle of rotation in radians (using deg2rad so can be set in degrees)
% Get corners of rectangle
corners = [c(1) + w/2, c(2) + h/2; c(1) + w/2, c(2) - h/2; c(1) - w/2, c(2) - h/2; c(1) - w/2, c(2) + h/2];
% rotate corner points
corners = [(corners(:,1)-c(1))*cos(a) - (corners(:,2)-c(2))*sin(a) + c(1), (corners(:,1)-c(1))*sin(a) + (corners(:,2)-c(2))*cos(a) + c(2)];
% Use 'fill' or 'patch' to plot
fill(corners(:,1), corners(:,2), 'r')

如果你想重用它,可以打包成一个函数

function [corners(:,1), corners(:,2)] = getRectangle(c, h, w, a)
% This function returns the corner points for a rectangle, specified
% by its centre point c = [x,y], height h, width w and angle in degrees from horizontal a
    a = deg2rad(a);
    corners = [c(1) + w/2, c(2) + h/2; c(1) + w/2, c(2) - h/2; c(1) - w/2, c(2) - h/2; c(1) - w/2, c(2) + h/2];
    corners = [(corners(:,1)-c(1))*cos(a) - (corners(:,2)-c(2))*sin(a) + c(1), (corners(:,1)-c(1))*sin(a) + (corners(:,2)-c(2))*cos(a) + c(2)];
end

使用:

[rectX, rectY] = getRectangle([0,0], 5, 8, 30);
fill(rectX, rectY, 'r');