I have a problem with Mathematica's symbolic manipulations. As an example, consider the following expression:

$$\sum _{i=1}^n -2 x_i \left(-a x_i-b+y_i\right)=0$$

How do I get Mathematica to expand it into this form:

$$-\sum _{i=1}^n x_i y_i +a \sum _{i=1}^n x_i^2+b \sum _{i=1}^n x_i=0$$

What I mean is: what functions do I apply to get the product to expand and the summation operator to distribute?

  • 1
    $\begingroup$ You are requesting two changes: first to Expand the products in the summation and second to Distribute the action of Sum over the addition. Consulting the help pages for Expand and Distribute will answer your question. $\endgroup$
    – whuber
    Dec 26, 2012 at 18:15

2 Answers 2

Distribute @ Sum[-2 Subscript[x, i] (-a Subscript[x, i] - b + Subscript[y, i]) // Expand,
                 {i, n}] == 0

enter image description here

  • 1
    $\begingroup$ How can one make the 2a and 2b factors come out in front of the sums? (and in general any variables that do not depend on the summation index)? $\endgroup$
    – Andrei
    May 9, 2013 at 13:26
  • $\begingroup$ One can play with pattern matching, e.g. let the resulting expression be expr, then expr /. {Sum[Times[c_, d__], List[i_, n_]] :> c Sum[Times[d], List[i, n]]} does what you want. In more general cases one can work with ReplaceRepeated (//.) and (or) restrict pattern like e.g. c_?NumericQ. $\endgroup$
    – Artes
    May 9, 2013 at 14:09

I had this question also a few times, but I never bothered to solve it properly. Here is my solution, which also moves constant factors out of the sums:

SumExpand[exp_] := exp /. Sum[c_, {i_, a_, b_}] :> Distribute[Sum[ExpandAll[c], {i, a, b}]]
SumSimplify[exp_] := SumExpand[exp] /. Sum[c_, {i_, a_, b_}] :> Apply[Times, Extract[c, Position[D[c /. Times -> List, i], 0]]] Sum[c/Apply[Times, Extract[c, Position[D[c /. Times -> List, i], 0]]], {i, a, b}]

Here is an example (linear regression):

err = Sum[(c0 + c1 x[i] - y[i])^2, {i, 1, n}]
gl1 = D[err, c0] // SumSimplify
gl2 = D[err, c1] // SumSimplify

The results are: $$err = \sum\limits_{i=1}^n (c_0 + c_1 x[i] - y[i])^2$$ $$gl1 = 2 c_0 n + 2 c_1 \sum\limits_{i=1}^n x[i] - 2 \sum\limits_{i=1}^n y[i]$$ $$gl2 = 2 c_0 \sum\limits_{i=1}^n x[i] + 2 c_1 \sum\limits_{i=1}^n x[i]^2 - 2 \sum\limits_{i=1}^n x[i] y[i]$$

The code

Solve[{gl1 == 0, gl2 == 0}, {c0, c1}]

gives the parameters $c_0$ and $c_1$.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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