Alternative to ginput for finding curve intersections with unevenly spaced data in MATLAB

9 ビュー (過去 30 日間)
Is there a better way to determine the intersection of two curves in MATLAB, other than using ginput, especially when the data points are unevenly spaced and do not include the exact intersection point? How can I handle cases where one of my datasets forms two angled lines joined together, rather than a smooth curve?

採用された回答

Matt J
Matt J 2025 年 2 月 8 日
編集済み: Matt J 2025 年 2 月 8 日
Use fminbnd or fzero,
x=sort(rand(1,12)*5);
y1=[0,1,-1*x(3:end)+3+2*x(3)];
y2=2*x-3;
f=@(z) interp1(x,y1,z)-interp1(x,y2,z) ;
xmin=fzero(f,[min(x),max(x)]); ymin=interp1(x,y1,xmin); %intersection
h=plot(x,y1,'--gx', x,y2,'--b+',xmin,ymin,'ro');
h(3).MarkerFaceColor=h(3).Color; h(3).MarkerSize=8;
  1 件のコメント
Bo
Bo 2025 年 2 月 8 日
Instead of using sort, I use [X,ia,ic] = unique(x); y1 = y1(ia); other than that, both fzero, and fminbnd works well, really appreciated!

サインインしてコメントする。

その他の回答 (2 件)

Alan Stevens
Alan Stevens 2025 年 2 月 8 日
Create a function using interp1 for use with fzero. For example:
yfn = @(X,Y,x) interp1(X,Y,x);
X = [1,2,3,7,8,9];
Y1 = X;
Y2 = 15-X.^1.5;
x0 = 6;
xp = fzero(@(x0)fn(x0,X,Y1,Y2,yfn),x0);
disp(xp)
4.5710
yp = yfn(X,Y1,xp);
plot(X,Y1,'-o',X,Y2,'-+',xp,yp,'ks'),grid
xlabel('x'), ylabel('y')
function Z = fn(x,X,Y1,Y2,yfn)
Z = yfn(X,Y1,x)-yfn(X,Y2,x);
end

Star Strider
Star Strider 2025 年 2 月 8 日
編集済み: Star Strider 2025 年 2 月 9 日
Another approach —
x = [linspace(0, 2.4) linspace(5.2, 7, 8)].'*1E-3;
y1 = [x(x<=2.4E-3)*580/2.4E-3; 500*ones(size(x(x>2.5E-3)))];
y2 = x*580/2.4E-3 - 450;
idx = find(diff(sign(y2 - y1)))
idx = 100
idxrng = max(1,idx) : min(numel(x),idx+1)
idxrng = 1×2
100 101
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
y2(idxrng)-y1(idxrng)
ans = 2×1
-450.0000 306.6667
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
xi = interp1((y1(idxrng)-y2(idxrng)), x(idxrng), 0)
xi = 0.0041
yi = interp1(x, y1, xi)
yi = 532.4229
figure
plot(x, y1, '.-', DisplayName="y_1")
hold on
plot(x, y2, '.-', DisplayName="y_2")
plot(xi, yi, 'sr', DisplayName="Intersection")
hold off
grid
legend(Location='best')
This approach finds the approximate index of the two lines and then interpolates to find the intersection points of the lines.
EDIT — (9 Feb 2025 at 1:43)
Corrected code.
.

カテゴリ

Help Center および File Exchange2-D and 3-D Plots についてさらに検索

製品


リリース

R2024b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by