Polyfit is giving incorrect coefficients for correct plot fit.
8 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
Stijn Haenen
on 26 Nov 2019
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')
More Answers (0)
See Also
Categories
Find more on Get Started with Curve Fitting Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!