如果matlab中两个矩形相交为零

时间:2017-05-26 11:06:45

标签: matlab 2d

通过x轴(水平轴)了解两个矩形的中心及其角度,如何在Matlab中识别它们的交点是否为零?任何包含此信息的答案都非常感谢。矩形的宽度和长度也是已知的

1 个答案:

答案 0 :(得分:0)

如果您想以数字方式解决这个问题,这是一个编程问题。对于精确解,您可以使用几何方程。

第一个问题:从宽度,高度和中心定义矩形的角落:

C1 = [0, 0];    % Centre of rectangle 1 (x,y)
C2 = [1, 1];    % Centre of rectangle 2 (x,y)
W1 = 5; W2 = 3; % Widths of rectangles 1 and 2
H1 = 2; H2 = 3; % Heights of rectangles 1 and 2
% Define the corner points of the rectangles using the above
R1 = [C1(1) + [W1; W1; -W1; -W1]/2, C1(2) + [H1; -H1; -H1; H1]/2];
R2 = [C2(1) + [W2; W2; -W2; -W2]/2, C2(2) + [H2; -H2; -H2; H2]/2];

下一个问题是创建许多代表矩形边缘的点。如果你想查看相交区域,你可以在矩形内生成许多点

n = 1000;       % Define some number of points to use
% Use interp1 to interpolate around the rectangles
R1points = interp1(1:5, [R1; R1(1,:)], linspace(1,5,n));
R2points = interp1(1:5, [R2; R2(1,:)], linspace(1,5,n));

然后旋转矩形:

a1 = deg2rad(0); a2 = deg2rad(30); % angles of rotation for rectangle 1 and 2 respectively
R1rotated(:,1) = (R1points(:,1)-C1(1))*cos(a1) - (R1points(:,2)-C1(2))*sin(a1) + C1(1);
R1rotated(:,2) = (R1points(:,1)-C1(1))*sin(a1) + (R1points(:,2)-C1(2))*cos(a1) + C1(2);
R2rotated(:,1) = (R2points(:,1)-C2(1))*cos(a2) - (R2points(:,2)-C2(2))*sin(a2) + C2(1);
R2rotated(:,2) = (R2points(:,1)-C2(1))*sin(a2) + (R2points(:,2)-C2(2))*cos(a2) + C2(2);

最后,检查与inpolygon的交叉点:

in1 = inpolygon(R1rotated(:,1), R1rotated(:,2), R2rotated(:,1), R2rotated(:,2));
in2 = inpolygon(R2rotated(:,1), R2rotated(:,2), R1rotated(:,1), R1rotated(:,2));

如果nnz(in1)>0nnz(in2)>0那么你有一个交集点!使用散点图形化它:

hold on
scatter(R2rotated(:,1),   R2rotated(:,2),   '.b')
scatter(R2rotated(in2,1), R2rotated(in2,2), 'xc')
scatter(R1rotated(:,1),   R1rotated(:,2),   '.r')
scatter(R1rotated(in1,1), R1rotated(in1,2), 'xg')

结果:

enter image description here