【问题标题】:How to determine the intersection of two graphs in MATLAB?如何在MATLAB中确定两个图的交集?
【发布时间】:2021-07-08 22:01:15
【问题描述】:

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

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

如果我画他们的图,会是这样的:

plot(a)
hold on
plot(b)

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

【问题讨论】:

    标签: matlab plot


    【解决方案1】:

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

    这主要分三步完成

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多