Polyfit is giving incorrect coefficients for correct plot fit.

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

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개)

카테고리

도움말 센터File Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

제품

릴리스

R2018a

태그

질문:

2019년 11월 26일

댓글:

2019년 11월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by