curve fit a custom polynomial
8 次查看(过去 30 天)
显示 更早的评论
I have the following 2nd order polynomial in the r-z coordinates:
Right now I have four sets of coordinats (r,z), how should I do a curve fit such that I can get an expression for Z in terms of r?
z = [-6.41 -12.4 2.143 102];
r = [13.58 15.7636 12.96 46.6];
0 个评论
采纳的回答
Star Strider
2021-10-27
One approach —
syms A B C D r z
sf = A*r^2 + B*z + C*r + D == 0
sfiso = isolate(sf, z)
zfcn = matlabFunction(rhs(sfiso), 'Vars',{[A B C D],r})
z = [-6.41 -12.4 2.143 102];
r = [13.58 15.7636 12.96 46.6];
B0 = rand(1,4);
nlm = fitnlm(r, z, zfcn, B0)
Bv = nlm.Coefficients.Estimate;
pv = nlm.Coefficients.pValue;
Out = table({'A';'B';'C';'D'},Bv,pv, 'VariableNames',{'Parameter','Value','p-Value'})
rv = linspace(min(r), max(r));
zv = predict(nlm, rv(:));
figure
plot(r, z, 'pg')
hold on
plot(rv, zv, '-r')
hold off
grid
xlabel('r')
ylabel('z')
legend('Data','Model Fit', 'Location','best')
The Warning was thrown because the number of parameters are not less than the number of data pairs.
Experiment to get different results.
.
2 个评论
Star Strider
2021-10-27
As always, my pleasure!
syms A B C D r z
sf = A*r^2 + B*z + C*r + D == 0
sfiso = solve(sf, z)
zfcn = matlabFunction(sfiso, 'Vars',{[A B C D],r})
z = [-6.41 -12.4 2.143 102];
r = [13.58 15.7636 12.96 46.6];
B0 = rand(1,4);
nlm = fitnlm(r, z, zfcn, B0)
Bv = nlm.Coefficients.Estimate;
pv = nlm.Coefficients.pValue;
Out = table({'A';'B';'C';'D'},Bv,pv, 'VariableNames',{'Parameter','Value','p-Value'})
rv = linspace(min(r), max(r));
zv = predict(nlm, rv(:));
figure
plot(r, z, 'pg')
hold on
plot(rv, zv, '-r')
hold off
grid
xlabel('r')
ylabel('z')
legend('Data','Model Fit', 'Location','best')
I like isolate because of the output format, and some of its other characteristics.
.
更多回答(1 个)
Rik
2021-10-27
You have two options: rewrite your equation to be a pure quadratic and use polyfit, or use a function like fit or fminsearch on this shape.
If you have trouble implementing either of these two, feel free to comment with what you tried.
2 个评论
Rik
2021-10-27
Polyfit will fit a pure polynomial of the form
f(x)=p(1)*x^n +p(2)*x^(n-1) ... +p(n)*x +p(n+1)
That means you can determine the values of -A/B, -C/B, and -D/B with polyfit.
As you may conclude from this: there is no unique solution for your setup, unless you have other restrictions to the values you haven't told yet.
z = [-6.41 -12.4 2.143 102];
r = [13.58 15.7636 12.96 46.6];
p=polyfit(r,z,2)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Linear and Nonlinear Regression 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!