3
$\begingroup$

I have very large expression and I want to extract and sum up all the numerical coefficients which multiply the summands.

For example,

expr = x + 2*y + 3*z*w 

What I need is for Mathematica to do is to extract the numerical coefficients {1, 2, 3} and sum them up, 1+2+3=6.

I cannot use Coefficient function, because the expressions (represented by x, y, z and w in the above example) are very complicated, and the summation is huge.

Does anyone have any suggestions how to solve this? Thank you.

$\endgroup$
1
  • 1
    $\begingroup$ Maybe you could provide an example of one of the complex expressions you mentioned? This would help in finding a solution, which might really fit your needs. $\endgroup$ Commented Mar 11, 2015 at 13:26

2 Answers 2

3
$\begingroup$

It is quite possible that details matter. Without those, we can only guess what could be useful:

Cases[expr, x_. y___ :> x, {1}] (*{1} is redundant, just wanted to stress it out *) % // Total 
{1, 2, 3} 6 
$\endgroup$
2
  • $\begingroup$ Ahhh! I edited the wrong post!! So sorry! $\endgroup$ Commented Mar 11, 2015 at 12:50
  • $\begingroup$ @MichaelE2 No problem ;) $\endgroup$ Commented Mar 11, 2015 at 12:50
3
$\begingroup$

Ditto what Kuba said about details. Another guess:

expr /. Thread[Variables[expr] -> 1] (* 6 *) 

I guess it works for polynomials. It's not really clear to me what the coefficients of Exp[x] are. (It might be 1 Exp[1 x], etc.) Or (x + y)^2 vs. x^2 + 2 x y + y^2. (This answer gives the sum of the coefficients of the latter.)


Another interpretation, assuming expr has the head Plus:

coeff[term_Times] := Times @@ Cases[term, _?NumericQ]; coeff[term_?NumericQ] := term; coeff[term_] := 1; coeff /@ expr (* 6 *) coeff /@ (3 - x^2 + 2 Sqrt[2] x y - Sin[2] Sin[z] + (x + y)^2) (* 3 + 2 Sqrt[2] - Sin[2] *) 

Note in this interpretation (x + y)^2 is treated as an atomic term with coefficient 1.

$\endgroup$
4
  • $\begingroup$ It works quite nice, I wasn't aware what can be taken as variable. +1 $\endgroup$ Commented Mar 11, 2015 at 12:51
  • $\begingroup$ Do you know why Variables /@ {Sin[x], Exp[x]}? $\endgroup$ Commented Mar 11, 2015 at 12:53
  • $\begingroup$ @Kuba Variables works well on polynomials. I guess Sin[_] and Cos[_] are considered "variables." I suppose for trig. equations. $\endgroup$ Commented Mar 11, 2015 at 12:53
  • $\begingroup$ @Luka You're welcome. Out of curiosity, which one? $\endgroup$ Commented Mar 11, 2015 at 15:37

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.