Need help with a least squares method fitting.

1 次查看(过去 30 天)
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;
clc;
load('data')
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)];
a=N/q
%Polyfit Check to compare
x=[t]';
y=[r]';
b=polyfit(x,y,2)
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 *
0.0000
0.0001
1.5963
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

回答(1 个)

James Tursa
James Tursa 2017-11-7
编辑:James Tursa 2017-11-7
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

类别

Help CenterFile Exchange 中查找有关 Descriptive Statistics 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by