2
$\begingroup$

If I evaluate Sum[(x + Subscript[y, n])^2, n] + (y + z)^2 // ExpandAll then the expression within the Sum is not expanded, yet if it is replaced with another function such as Sin the inner expression is expanded. Why is this the case and how do I get the desired behaviour?

$\endgroup$
1
$\begingroup$

Inactivate might be helpful here:

exp = Inactivate[Sum[(x + y[n])^2, n] + (y + z)^2, Sum];

Activate[ExpandAll[exp]]
(*y^2 + 2*y*z + z^2 + Sum[x^2 + 2*x*y[n] + y[n]^2, n]*)
$\endgroup$
0
$\begingroup$

It doesn't work because Sum has the attribute HoldAll. You can see this effect with a made-up function,

ClearAll@fg
(fg[(x + y[n])^2, n] + (y + z)^2) // ExpandAll
SetAttributes[fg, HoldAll];
(fg[(x + y[n])^2, n] + (y + z)^2) // ExpandAll
(* y^2 + 2 y z + z^2 + fg[x^2 + 2 x y[n] + y[n]^2, n] *)
(* y^2 + 2 y z + z^2 + fg[(x + y[n])^2, n] *)

(I replaced your Subscript[y,n] with y[n] because subscripts are bad mmkay) Before fg had the attribute, ExpandAll worked just as hoped, but with the attribute you can not expand within fg. I don't see a way to remove this attribute, nor an easy workaround. Here is something that works though,

ClearAll@f;
(Sum[(x + y[n])^2, n] + (y + z)^2) // # /. Sum -> f & // 
  ExpandAll // # /. f -> Sum &
(* y^2 + 2*y*z + z^2 + Sum[x^2 + 2*x*y[n] + y[n]^2, n] *)
$\endgroup$
  • $\begingroup$ If one must: MapAt[ExpandAll, Sum[(x + y[n])^2, n], 1]. $\endgroup$ – J. M. will be back soon Mar 23 '16 at 13:27
  • $\begingroup$ But MapAt[ExpandAll, Sum[(x + y[n])^2, n] + (y + z)^2, {1}] doesn't do the trick, you have to resort to mapping MapAt, MapAt[ExpandAll, #, 1] & /@ (Sum[(x + y[n])^2, n] + (y + z)^2) $\endgroup$ – Jason B. Mar 23 '16 at 13:32
  • $\begingroup$ Yes, it was intended as a special treatment for Sum[] objects. $\endgroup$ – J. M. will be back soon Mar 23 '16 at 13:33

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.