如果两个矩形交点在matlab中为零

If two rectangles intersection is zero in matlab

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

这是一道编程题,如果你想用数值求解的话。对于精确解,您可以使用几何方程。


第一个问题:根据矩形的宽度、高度和中心定义矩形的角:

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')

结果: