MATLAB Answers

Need help with a least squares method fitting.

2 views (last 30 days)
Grant Piephoff
Grant Piephoff on 7 Nov 2017
Edited: James Tursa on 7 Nov 2017
I am doing a final project for a class and the first part is about fitting a 2nd and 6th order polynomials to some data using the least squares method. The catch is the general linear least squares method cannot be used, i.e. {y}=[Z]{a}+{e}.
clear all;
x = [t]';
y = [r]';
N=[14400 sum(x) sum(x.^2);sum(x) sum(x.^2) sum(x.^3);sum(x.^2) sum(x.^3) sum(x.^4)];
q=[sum(y) sum(x.*y) sum(x.^2.*y)];
%Polyfit Check to compare
fprintf('The data is fit as y=(%.4f)+(%.4f)(x)+(%.4f)x^2\n\n',b(1),b(2),b(3));
And the results I get do not match up.
a =
1.0e+04 *
b =
1.0e+03 *
-0.0000 0.0001 8.0980
The data is fit as y=(-0.0000)+(0.1205)(x)+(8098.0146)x^2
I don't know exactly what I am doing wrong. The number 14400 is in there because the data is two 14401 X 1 doubles. I have also attached the data. Thanks in advance

Answers (1)

James Tursa
James Tursa on 7 Nov 2017
Edited: James Tursa on 7 Nov 2017
The least squares equations you are trying to solve, using your variable names, are
N * a = q'
So do this instead (where the transpose is simply to turn q into a column vector):
a = N \ q';
Then you can see how they match up (the fliplr stuff is just to get the numbers to line up for output):
>> fliplr((N\q')')
ans =
1.0e+003 *
-0.000000012897721 0.000120497278334 8.098014646584689
>> polyfit(x,y,2)
ans =
1.0e+003 *
-0.000000012897721 0.000120497278334 8.098014646584003

Community Treasure Hunt

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

Start Hunting!