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

2 visualizaciones (últimos 30 días)
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?

Respuesta aceptada

Star Strider
Star Strider el 9 de Nov. de 2023
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')
.

Más respuestas (2)

Les Beckham
Les Beckham el 9 de Nov. de 2023
Have you tried interp1?

MarKf
MarKf el 9 de Nov. de 2023
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)))

Categorías

Más información sobre MATLAB en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by