

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer

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.


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

share|improve this question
Probably related – Dr. belisarius Feb 15 '14 at 16:43
thanks belisarius, that's what i needed – phubaba Jun 18 '15 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;
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}];

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

Your Answer


