How to find the y from given x on fit line?
35 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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?
0 Kommentare
Antworten (4)
Image Analyst
am 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!
% 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)
0 Kommentare
Jeffrey Clark
am 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).
0 Kommentare
John D'Errico
am 12 Nov. 2022
Bearbeitet: John D'Errico
am 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:
mdl(.3)
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.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Smoothing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!