How to find the y from given x on fit line?
3 views (last 30 days)
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 (mathworks.com).
If you have a polynomial fit using Create and Evaluate Polynomials you can use Polynomial evaluation - MATLAB polyval (mathworks.com).
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
Now we can just use the resulting fitted model to predict any point as I do here:
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 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);
% 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);
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!
% 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);