I define $Y = a + b*x + e$, and I want to find values for $a,b,$ by least squares, so I minimize $RSS = sum((Y_i - a - b*x_i)^2)$

I then take derivatives, ${d RSS \over da} = 0$ and ${d RSS \over db} = 0$ and solve. Now if I put these formulas into Mathematica,

f2[a_, b_, y_, x_, n_] = Sum[(y[i] - a - b*x[i])^2, {i, n}] 

Solve[{D[f2[a, b, y, x, n], {a}] == 0, D[f2[a, b, y, x, n], {b}] == 0}, {a, b}]

I get the following error.

Solve::nsmet: This system cannot be solved with the methods available to Solve.

The derivatives work, but Mathematica doesn't know how to expand out the summations.

Any thoughts? I've tried Expand, Sum, Distribute (as suggested in some different expanding Sum questions).

I've also seen some thoughts on how to define Mathematica rules for summations (anyone have those?).


Here's one way to fix things. I've set values for x and y in arrays (rather than having them be undefined values of functions):

n = 10;
x = RandomInteger[{-10, 10}, n];
y = 3 x + RandomInteger[{-1, 1}, n]; 
f2[a_, b_, y_, x_, n_] = Sum[(y[[i]] - a - b*x[[i]])^2, {i, n}];
Solve[{D[f2[a, b, y, x, n], {a}] == 0, D[f2[a, b, y, x, n], {b}] == 0}, {a, b}]

{{a -> -(103/956), b -> 5699/1912}}
| improve this answer | |
  • $\begingroup$ thanks for the help, I was looking for a numerical way and it looks like belisarius' comment was what I needed $\endgroup$ – phubaba Jun 18 '15 at 20:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.