The Student Room Group

matlab, please help

I'm trying to do the polynomial curve-fitting part of this pdf (attached). I'm having trouble calculating the coefficients. I get no 0th order coefficient. I'm also having a lot of trouble with the ' \ ' operator because even when the length of v and A match up (or should do) it says the matrix size is wrong.

This is my code

function[] = C002v2_2()
start = 0;
fin = 200;
n = 100;
div = (fin - start)/n;
c1 = [1.5, -2.5, 0.7, -1.2];
e = 0.01;
x = start:div:fin;
y = x;
for i = 1:n
y(i) = c1(1) + c1(2) * x(i) + c1(3) * x(i)^2 + c1(4) * x(i)^3 + e * randn();
end
v = zeros(4,1);
for k = 1:4
for i = 1:n
v(k) = v(k) + y(i)*x(i)^k;
end
end
A = zeros(4, 3);
for k = 1:4
for i = 1:3
for j = 1:n
A(k,i) = A(k,i) + x(j)^(i+k);
end
end
end
%A
%v
c2 = A \ v;
%c2
yf = c2(1) + c2(2) * x + c2(3) * x.^2 + c2(4) * x.^3;
f = figure();
plot(x, y, x, yf);
end


Thanks so much. I'm desperate.
(edited 8 years ago)

Quick Reply

Latest

Trending

Trending