How to find the y from given x on fit line?

26 ビュー (過去 30 日間)
kivanc Koca
kivanc Koca 2022 年 11 月 12 日
回答済み: Image Analyst 2022 年 11 月 12 日
I have a fit line of a graph and I need to find the spesific y value for a x value that I determine. Is it possible?

回答 (4 件)

KSSV 2022 年 11 月 12 日
Yes very much it is possible. Read about interp1. Also have a look on polyfit and polyval.

Jeffrey Clark
Jeffrey Clark 2022 年 11 月 12 日
@kivanc Koca, if you have a fit using spline, pchip, makima, interp1, or the spline utility function mkpp you can use Evaluate piecewise polynomial - MATLAB ppval (

John D'Errico
John D'Errico 2022 年 11 月 12 日
編集済み: John D'Errico 2022 年 11 月 12 日
It completely depends on how you perform the fit. For example, with the curve fitting toolbox, just do this:
X = rand(10,1);
Y = cos(X);
mdl = fit(X,Y,'poly2') % quadratic fit to a cosine is probably adequate over a reasonably small interval
mdl =
Linear model Poly2: mdl(x) = p1*x^2 + p2*x + p3 Coefficients (with 95% confidence bounds): p1 = -0.4559 (-0.4637, -0.4481) p2 = -0.01716 (-0.02471, -0.009607) p3 = 1.002 (1, 1.003)
Now we can just use the resulting fitted model to predict any point as I do here:
ans = 0.9554
Other fitting tools, for example, polyfit, also have evaluation tools provided with them, so you can use polyval to evaluate a polynomial model from polyfit. Read the help for the tool you used to perform the fit.

Image Analyst
Image Analyst 2022 年 11 月 12 日
You can use polyfit and polyval. Here is a full demo. Don't be afraid, the actual code is only 2 lines. The rest is just code to create the variables and do some fancy plotting.
x = sort(10 * rand(1, 10));
y = 0.5 * x + 0.3 * rand(1, length(x));
% Plot the original points.
plot(x, y, 'b.', 'MarkerSize', 30);
grid on;
xlabel('x', 'FontSize',20)
ylabel('y', 'FontSize',20)
% Fit a line through the points.
coefficients = polyfit(x, y, 1); % YOU NEED THIS LINE!
% Get a fit. Find the fit values everywhere, even between the original points, just for fun.
xFit = linspace(min(x), max(x), 1000);
yFit = polyval(coefficients, xFit);
hold on;
plot(xFit, yFit, 'r-', 'LineWidth', 2)
% Find the y location where x equals exactly 6.
xDesired = 6;
xline(xDesired, 'Color', 'g', 'LineWidth',2)
yDesired = polyval(coefficients, xDesired) % YOU NEED THIS LINE!
yDesired = 3.1371
% Draw a line from the y axis to the fit line and report what the y value
% is in the title of the graph.
line([0, xDesired], [yDesired, yDesired], 'Color', 'g', 'LineWidth', 2)
caption = sprintf('y = %f when x = %.1f', yDesired, xDesired);
title(caption, 'FontSize',20)


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