matlab - 如何在MATLAB中确定两个图的交集?
问题描述
例如,我有以下两个变量:
a = [1, 3, 5, 3, 1];
b = [0, 4, 2, 4, 6];
如果我画他们的图,它将如下:
plot(a)
hold on
plot(b)
我想指定两个图的交集。也就是说,如果红色图表在蓝色图表上方,它会显示一个实心红点。如果红色图表下降到蓝色图表,红点表示空虚。(就像下面的照片)
解决方案
下面的代码给出了想要的结果。
这主要分三步完成
获取发生交叉的点,由
diff(a>b)
非零标识,即两者中哪个较大的变化。计算出发生交叉的相关线段的直线方程
在这些点处绘制填充或空心标记
第 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
推荐阅读
- react-native - View network traffic using react native debugger
- android - recyclerview 中的 EditText 被键盘覆盖
- linq - LINQ 父子集合
- c - 整数之和,不包括 13 和 13 之后的数字
- google-sheets - 如果文本包含数字,谷歌电子表格条件格式
- arrays - 如何在一组坐标中找到最大的 x,y 坐标?
- sql - 使用 Oracle REGEXP_SUBSTR 提取下划线分隔的大写数据
- r - 如何在 r 中的多行上迭代地使用 mutate
- sql - 将 VARCHAR 转换为 XML,包括 < (<) , > (>)
- php - Laravel 中的 MethodNotAllowedHttpException,Request::isMethod('') 不起作用