Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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

share|improve this question
    
Probably related mathematica.stackexchange.com/a/16378/193 –  belisarius Feb 15 at 16:43

1 Answer 1

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}}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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