Displaying fit function on the plot

조회 수: 66 (최근 30일)
uzzi
uzzi 2023년 4월 13일
답변: Steven Lord 2023년 4월 13일
Hello,
I have a fit function which is displayed below. There is a plot with this fitted function. Are there anyway that I can display the "f(x) = -0,02462x^2 - 8.336x -747.7" on the plot?
If someone know how to do it, pls help me.

답변 (1개)

Steven Lord
Steven Lord 2023년 4월 13일
We can use some of the methods of the object returned by fit to get the pieces we need to display it.
x = (1:10).';
y = x.^2 + 2*x - 3 + randn(size(x));
P = fit(x, y, 'poly2')
P =
Linear model Poly2: P(x) = p1*x^2 + p2*x + p3 Coefficients (with 95% confidence bounds): p1 = 0.9567 (0.8564, 1.057) p2 = 2.46 (1.328, 3.592) p3 = -3.834 (-6.544, -1.124)
The formula method gives us the expression for the fit with the coefficient names.
F = formula(P)
F = 'p1*x^2 + p2*x + p3'
The coeffnames method gives us the coefficient names and the coeffvalues method the coefficient values.
N = coeffnames(P);
V = coeffvalues(P);
Now we can use string operations to replace the coefficient names with the coefficient values (converted to strings.)
formulaWithValues = replace(F, string(N).', string(V))
formulaWithValues = '0.95673*x^2 + 2.4599*x + -3.834'
That + followed by a - for the constant term is a little awkward looking. Let's fix that.
formulaWithValues = replace(formulaWithValues, "+ -", "- ")
formulaWithValues = '0.95673*x^2 + 2.4599*x - 3.834'
Now we could use formulaWithValues to add a legend entry for the fitted curve (or with the text function to put it in the axes itself.)
plot(x, y, 'o', DisplayName = 'raw data')
hold on
xx = 1:0.25:10;
plot(xx, P(xx), DisplayName = formulaWithValues)
legend show
This gets a little more complicated if your fit has problem-dependent parameters, but it wouldn't be that difficult to use probnames and probvalues in addition to coeffnames and coeffvalues.

카테고리

Help CenterFile Exchange에서 Get Started with Curve Fitting Toolbox에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by