4
$\begingroup$

I found out that,it is INCREDIBLY(like 100 times) faster to use Dot instead of Sum,to perform long sums. But I have not been able to use this alternative to perform the following sum:

a={{b,c},{d,e}};

a[[1]]+a[[2]]

I want to get this output:

{b,c}+{d,e}={b+d,c+e}

I tried:

a.{1,1}

but did not work.

The easy way to do it is:

Sum[a[[i]],{i,1,2}];

But I want to avoid this slow way. Any faster alternative?

$\endgroup$
3
  • 3
    $\begingroup$ Have you looked at using Total? $\endgroup$
    – chuy
    Commented Sep 5, 2013 at 17:40
  • $\begingroup$ NO did not. I will try that... $\endgroup$
    – Mencia
    Commented Sep 5, 2013 at 17:41
  • 1
    $\begingroup$ @chuy Actually it's just Total[a] in this case. What your input does is more simply done as Total[a, {2}]. $\endgroup$
    – Szabolcs
    Commented Sep 5, 2013 at 17:44

2 Answers 2

21
$\begingroup$

Sum is meant for working with symbolic sums (check the examples in the docs to see what I mean). What you are looking for here is Total:

Total[a]

(* ==> {b+d,c+e} *)

Before we had this shorthand, we used Plus with Apply:

Plus @@ a

(* ==> {b+d,c+e} *)

The most important difference between using Total and Plus is that Total is optimized for performance. Plus will always do compensated summation while this needs to be explicitly turned on in Total using Method -> CompensatedSummation.

Both can be used at various levels or ranges of levels. Compare Total[a, {2}] with Apply[Plus, a, {1}].

$\endgroup$
2
  • $\begingroup$ Good ol´ times, eh? I find Plus@@a also especially educational... $\endgroup$
    – Yves Klett
    Commented Sep 5, 2013 at 17:47
  • 2
    $\begingroup$ It seems that Plus is not entirely equivalent to Total with compensated summation, ref: mathematica.stackexchange.com/q/103771/121 $\endgroup$
    – Mr.Wizard
    Commented Aug 11, 2017 at 16:42
7
$\begingroup$

Or, in keeping with the request to use Dot, you can restate it as a vector/matrix product

{1, 1}.a

{b+d,c+e}
$\endgroup$

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.