# Thread: Least Squares Fit- Matlab

1. ## Least Squares Fit- Matlab

Not sure if this is in the right section. Im in an advanced engineering math class where our professor gives us labs with accompaning tutorials that usually do the lab for us (with a few number changes and a little knowledge of matlab), but the most recent lab is giving me trouble.

Here is the sample:
Find the least-squares fit at the points xi = 0, 1, 2, 3
of f(x) = 1+x2 by (a)y = Ax3 +B,
(b) y = CeDx,
(c) y = Ax + B,.
Find E2(f) for each case. Which one is better?

His code and results:
x=0:3; x=x’,
f=inline(’1+x.^2’); y=f(x);
A=[x.^3 ones(4,1)]; b=y; s=A\b,
E2=norm(b-A*s,2)/sqrt(4),
A=[ones(4,1) x]; b=log(y); s=A\b
g=exp(s(1)+s(2)*x),
E2=norm(g-y,2)/sqrt(4)
A=[x ones(4,1)]; b=y; s=A\b
E2=norm(b-A*s,2)/sqrt(4)
s =
3.0000
-0.0000
E2 =
1

Here is the actual lab:

Find the least-squares fit at the points xi = 1, 2, 3, 4
of f(x) = 2.3 − 3.7x3 by y = A + Bx Find E2(f).

Here is my attempt and results:

x=[1 2 3 4]' ;
f=inline( ' 2.3 － 3.7*x.^3 ' ); y=f(x);
A=[x ones(4,1)]; b=y; s=A\b
E2=norm(b-A*s,2)/sqrt(4)
s =

-76.9600
102.2000

E2 =

27.8608

When i submitted this, I was given an incorrect and told to redo it (we submit electronically)...I would like to resubmit by midnight if possible as that cutoff takes off more points, but any help would be greatly appreciated...I just dont really understand what to do/what im doing wrong.

Thanks

2. Originally Posted by ts9818a
Not sure if this is in the right section. Im in an advanced engineering math class where our professor gives us labs with accompaning tutorials that usually do the lab for us (with a few number changes and a little knowledge of matlab), but the most recent lab is giving me trouble.

Here is the sample:
Find the least-squares fit at the points xi = 0, 1, 2, 3
of f(x) = 1+x2 by (a)y = Ax3 +B,
(b) y = CeDx,
(c) y = Ax + B,.
Find E2(f) for each case. Which one is better?

His code and results:
x=0:3; x=x’,
f=inline(’1+x.^2’); y=f(x);
A=[x.^3 ones(4,1)]; b=y; s=A\b,
E2=norm(b-A*s,2)/sqrt(4),
A=[ones(4,1) x]; b=log(y); s=A\b
g=exp(s(1)+s(2)*x),
E2=norm(g-y,2)/sqrt(4)
A=[x ones(4,1)]; b=y; s=A\b
E2=norm(b-A*s,2)/sqrt(4)
s =
3.0000
-0.0000
E2 =
1

Here is the actual lab:

Find the least-squares fit at the points xi = 1, 2, 3, 4
of f(x) = 2.3 − 3.7x3 by y = A + Bx Find E2(f).

Here is my attempt and results:

x=[1 2 3 4]' ;
f=inline( ' 2.3 － 3.7*x.^3 ' ); y=f(x);
A=[x ones(4,1)]; b=y; s=A\b
E2=norm(b-A*s,2)/sqrt(4)
s =

-76.9600
102.2000

E2 =

27.8608

When i submitted this, I was given an incorrect and told to redo it (we submit electronically)...I would like to resubmit by midnight if possible as that cutoff takes off more points, but any help would be greatly appreciated...I just dont really understand what to do/what im doing wrong.

Thanks
Note that A and B in the form to be fitted have the opposite meaning from the model question, so I think we need:

A=[ones(4,1) x];

CB