How to find the y from given x on fit line?
35 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(4 个)
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!
% 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 个评论
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 (mathworks.com).
If you have a polynomial fit using Create and Evaluate Polynomials you can use Polynomial evaluation - MATLAB polyval (mathworks.com).
0 个评论
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
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Smoothing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!