首页 > 解决方案 > 如何在MATLAB中确定两个图的交集?

问题描述

例如,我有以下两个变量:

a = [1, 3, 5, 3, 1];
b = [0, 4, 2, 4, 6];

如果我画他们的图,它将如下:

plot(a)
hold on
plot(b)

a 和 b 的图

我想指定两个图的交集。也就是说,如果红色图表在蓝色图表上方,它会显示一个实心红点。如果红色图表下降到蓝色图表,红点表示空虚。(就像下面的照片)

想要的情节

标签: matlabplot

解决方案


下面的代码给出了想要的结果。

阴谋

这主要分三步完成

  1. 获取发生交叉的点,由diff(a>b)非零标识,即两者中哪个较大的变化。

  2. 计算出发生交叉的相关线段的直线方程

  3. 在这些点处绘制填充或空心标记

第 2 步可以说是最棘手的,我一直很懒惰,习惯于polyfit在每个标记位置的两个周围点之间拟合一条直线,这可能不是很有效,但它不需要太多思考就可以工作!

% Input
a = [1, 3, 5, 3, 1];
b = [0, 4, 2, 4, 6];

% Helper arrays to detect rise/fall in crossings
x = 1:numel(a);
idx = [0, diff(a > b)];
incIdx = idx == 1;
decIdx = idx == -1;

% Plot
figure(10); clf; hold on
plot(x,a);
plot(x,b);
for ii = 1:numel(idx)
    if decIdx(ii) || incIdx
        % Rise or fall, get the crossing point
        [xc,yc] = crossing( x(ii-1:ii), a(ii-1:ii), b(ii-1:ii) );
        % Plot filled or hollow marker as desired
        if incIdx(ii)
            plot( xc, yc, 'or', 'markersize', 10 );
        elseif decIdx(ii)
            plot( xc, yc, 'or', 'markersize', 10, 'MarkerFaceColor', 'r' );
        end
    end
end


function [xc,yc] = crossing(x,y1,y2)
    % Find intersection of lines with two shared x axis value pair and 
    % given pairs of y values
    p1 = polyfit(x,y1,1);
    p2 = polyfit(x,y2,1);    
    xc = (p2(2)-p1(2))/(p1(1)-p2(1));
    yc = p1(1)*xc + p1(2);
end

推荐阅读