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개)

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 CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by