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

3 views (last 30 days)
kivanc Koca
kivanc Koca on 12 Nov 2022
Answered: Image Analyst on 12 Nov 2022
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?

Answers (4)

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

Jeffrey Clark
Jeffrey Clark on 12 Nov 2022
@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 on 12 Nov 2022
Edited: John D'Errico on 12 Nov 2022
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 on 12 Nov 2022
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)


Find more on Interpolation in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!