How do i find x from given y that is closest to my peak or at x=0?

2 ビュー (過去 30 日間)
Roan Jansen
Roan Jansen 2023 年 11 月 9 日
コメント済み: Star Strider 2023 年 11 月 10 日
I have this graph:
I want to find the value of x at a given y = -6.
When i use (or something similar):
knnsearch(y,-6)
or
find((x-x0))
I get the value from x at the right side of the graph.
Is there a way to find the value of x at y = -6 which is close to my peak or at x = 0?

採用された回答

Star Strider
Star Strider 2023 年 11 月 9 日
One approach —
x = linspace(-10,10,500);
y = 1 - x.^2;
L = numel(x);
yval = -6;
zxi = find(diff(sign(y -yval)));
for k = 1:numel(zxi)
idxrng = max(1, zxi(k)-1) : min(L,zxi(k)+1);
xv(k) = interp1(y(idxrng), x(idxrng), yval);
end
xv
xv = 1×2
-2.6457 2.6457
figure
plot(x, y)
hold on
plot(xv, zeros(size(xv))+yval, 'sk')
hold off
grid
yline(yval, ':r')
.
  2 件のコメント
Roan Jansen
Roan Jansen 2023 年 11 月 10 日
Thanks this worked for me,
Star Strider
Star Strider 2023 年 11 月 10 日
As always, my pleasure!

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

その他の回答 (2 件)

Les Beckham
Les Beckham 2023 年 11 月 9 日
Have you tried interp1?

MarKf
MarKf 2023 年 11 月 9 日
I'm assuming you just have the data points of the line and not the function otherwise the question would be answered with the most linear algebraic solution. Also "x value close to" wouldn't make sense otherwise, tho not sure if you want "the (single) value of x close(st)" or both points like in @Star Strider's solution.
Still, you could simply find the point closest to 0 with min(abs(ys+6)), tho you do come across the issue of potentially capturing other points on the curve that are not close to the peak (like in 8<x<10 in your example or in 3<x<4 in the plot below). You could add another condition of being closest to the peak or by more simply restricting the comparison to the segment which includes it, which you could find with findpeaks (if you don't already know where it is).
xs = -1:0.023:4;
ys = xs.^3-4*xs.^2+xs-5;
plot(xs,ys), hold on, plot(xs,ones(size(xs))*-6)
[~,mini] = min(abs(ys+6));
plot(xs(mini),ys(mini),'o')
%alternatively subsect xs and ys to [-1,1] or
% [~,pki] = findpeaks(ys);
% [~,mini] = min(abs(ys+6)+abs(xs-xs(pki)))

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by