Identifying x value at y on an xy plot

5 ビュー (過去 30 日間)
Hannah Douglas
Hannah Douglas 2019 年 11 月 21 日
コメント済み: Star Strider 2019 年 11 月 21 日
I have a fairly simple problem that I imagine has a simple solution. I have a plot in which the x-axis represents a location (0-8) and the y-axis is the probability of a certain action occuring at that location. I need to identify the x value when there is a 50% chance of the action happening. Example data below.
x = [0,1,2,3,4,5,6,7,8];
y = [0,0,0,.25,.25,.25,.75,1,1];
plot(x,y);
line([0,8],[.5,.5]);
I just need to identify the x value when y is 0.5. Is there a simple solution I am missing here? Thank you!

採用された回答

Star Strider
Star Strider 2019 年 11 月 21 日
A common problem interpolating y-values that are not unique is how to make them appropriate for interpolation. One way is to simply choose a small range of data in the vicinity of the desired interpolation point.
Try this:
x = [0,1,2,3,4,5,6,7,8];
y = [0,0,0,.25,.25,.25,.75,1,1];
idx = find(y <= 0.5, 1, 'last'); % Select Small Range Of Data Based On Desired Interpolation Point
idxrng = [0 1]+idx;
Lxq = interp1(y(idxrng), x(idxrng), 0.5, 'linear'); % Interpolate Over Small Range Of Data
Pxq = interp1(y(idxrng), x(idxrng), 0.5, 'spline'); % Interpolate Over Small Range Of Data
figure
plot(x,y)
hold on
plot(Lxq, 0.5, 'p')
hold off
line([0,8],[.5,.5]);
Here the two interpolation menthods give the same result. That may not always be the situation, so specify an appropriate method.
Experiment to get different results.
  2 件のコメント
Hannah Douglas
Hannah Douglas 2019 年 11 月 21 日
This solution works really well for me, thank you! So far the linear and spline interpolation produce the same value, but I'll keep them both in for comparison. Thanks
Star Strider
Star Strider 2019 年 11 月 21 日
As always, my pleasure!
The linear and spline methods produce the same result in this example. However in different situations they would produce significantly different results, the reason I recommend always specifying a method to get the desired result. (The linear method is the default with interp1.)

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

その他の回答 (1 件)

dpb
dpb 2019 年 11 月 21 日
P=0.5; % P to find
iy=find(y>P,1); % first point past P
xp=interp1(y(iy-1:iy),x(iy-1:iy),P); % interpolate between prior point and point
You'll have problem where your proability points are identical between observations, though.

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by