Polyfit is giving incorrect coefficients for correct plot fit.

10 ビュー (過去 30 日間)
N O'SS
N O'SS 2019 年 11 月 26 日
コメント済み: N O'SS 2019 年 11 月 27 日
So when using polyfit I get a really nice line ploted and matches my data well. Unfortunately when I go to use the coefficients determined by polyfit, it doesn't make sense at all! My expected slope c(1) is around 0.3 but I'm getting around 6. Even when I do the approximate calculation of the slope by hand it is as expected so my data mustn't be wrong.
Here's my code...
N=10:10:60;
t1 = [3.5 6.5 10 12.5 15.5 19];
t2 = [3 6.5 10 13 16 20];
t3 = [3 7 10.5 13.5 17 20];
t4 = [4 7 10 13 16.5 20];
t5 = [3.5 7 11 14.5 18 20.5];
T = [t1;t2;t3;t4;t5];
m = mean(T);
%Linear fit using polyfit
[c,S,mu] = polyfit(N,m,1);
%Error values of coefficients
ci = polyparci(c,S);
% Display evaluated equation y = m*x + b and the wavelength (desired to be approx. 0.6 micrometers)
disp(['Equation is y = ' num2str(c(1)) '*x + ' num2str(c(2))])
disp(['Wavelength is ' num2str(2.*c(1)) ' micrometers'])
% Evaluate fit equation using polyval
[y_est, delta] = polyval(c,N,S,mu);
%Polyfit function from coefficients
f = c(1)*N + c(2);
hold on
%Plotting of data
scatter(N,m,'b')
%Plotting of linear fit from polyval
plot(N,y_est,'r')
%Plotting of linear fit from function with coefficients
plot(N,f,'g')
%Labelling axes and plot etc...
hold off
I've added a plot of the function of the function with the coefficients
f = c(1)*N + c(2);
plot(N,f,'g')
to show how they are incorrect. This is the plot it outputs.
I thought I used polyfit correctly but I must not have. Where have I gone wrong?

採用された回答

Stijn Haenen
Stijn Haenen 2019 年 11 月 26 日
If I run this script i get a good fit, see image
N=10:10:60;
t1 = [3.5 6.5 10 12.5 15.5 19];
t2 = [3 6.5 10 13 16 20];
t3 = [3 7 10.5 13.5 17 20];
t4 = [4 7 10 13 16.5 20];
t5 = [3.5 7 11 14.5 18 20.5];
T = [t1;t2;t3;t4;t5];
m = mean(T);
[c] = polyfit(N,m,1);
f = c(1)*N + c(2);
plot(N,f,'g')
hold on
scatter(N,m,'b')
  1 件のコメント
N O'SS
N O'SS 2019 年 11 月 27 日
Ah it worked when I removed the mu from the equation and it worked. Why does that happen? I thought mu just helps with calculating the error, but as I removed it the errors still worked.
Thank you for your help!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGet Started with Curve Fitting Toolbox についてさらに検索

タグ

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by