Reputation: 1771
I'm having trouble getting a quadratic line of best fit in Matlab. We aren't allowed to use the built-in line of best fit functions, but instead have to calculate it. This is what I have:
dat = load('co2.dat');
x = dat(:,1);
y = dat(:,2);
X = [ones(size(x)),x.^2];
z = X'*y;
S = X'*X;
U = chol(S);
w = U'\z;
c = U\w
axis tight;
plot(x,y,'o')
q = 1959:2:2012;
fit = c(1)+c(2)*q;
hold on
plot(q,fit,'r');
This just draws a horizontal line at -1000. If I get rid of the .^2
in the 4th line, it does a linear fit perfectly. Perhaps my problem rests more in my lack of knowledge with least squares than with Matlab, but, either way, I'm stumped (advise if this should be moved to the math forum). Any advice?
Upvotes: 0
Views: 573
Reputation: 12689
I changed two lines of yours:
X=[ones(size(x)), x, x.^2];
and,
fit = c(1)+c(2)*q+c(3)*q.^2;
Please have a try, thx.
Upvotes: 2