# Deriving least-squares equations in Mathematica

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?).

-
Probably related mathematica.stackexchange.com/a/16378/193 – belisarius has settled Feb 15 '14 at 16:43
thanks belisarius, that's what i needed – phubaba Jun 18 at 20:21

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;