11
$\begingroup$

I'm simply looking for the {}+{} function for sublist elements of a list: (Parallel sums of elements)

c = {{1, 2, 3, 4}, {8, 7, 6, 5}};
Plus[c]
Mean[c]  
desired={9, 9, 9, 9}

Where Mean does directly what it's supposed to, unfortunately Plus doesn't. I tried Take and Part but they both do not seem to work here . Additionally, my c consists of a varying number of elements. I tried to work with Length[c] and Range .. ({}+{} is no solution as list element number varies) thank you for help!!

$\endgroup$
19
$\begingroup$

Use either

Plus@@c

or

Total[c]
$\endgroup$
  • 12
    $\begingroup$ For completeness: if one treats the list of lists as a matrix, Total[c] and Total[c, {1}] sums columns, Total[c, {2}] sums rows, and Total[c, 2] sums all elements. $\endgroup$ – J. M. is away Feb 15 '12 at 23:29
  • 3
    $\begingroup$ @J.M. Good points. For once, I did not try to be complete :) $\endgroup$ – Leonid Shifrin Feb 15 '12 at 23:35
  • 5
    $\begingroup$ Leonid, are you ill? :o) $\endgroup$ – Mr.Wizard Feb 16 '12 at 5:10
  • $\begingroup$ @Mr.Wizard Looks like that :) $\endgroup$ – Leonid Shifrin Feb 16 '12 at 13:36
10
$\begingroup$

Before version 5, I used Tr a lot for summing vectors as Total wasn't available:

c = {{1, 2, 3, 4}, {8, 7, 6, 5}};
Tr /@ Transpose[c]

(*
==> {9, 9, 9, 9}
*)
$\endgroup$
7
$\begingroup$

Use

Apply[Plus, {{1, 2, 3, 4}, {8, 7, 6, 5}}]
(*
==> {9, 9, 9, 9}
*) 

or its shortcut

Plus @@ {{1, 2, 3, 4}, {8, 7, 6, 5}}

Another way is

MapThread[Plus, {{1, 2, 3, 4}, {8, 7, 6, 5}}]
$\endgroup$
4
$\begingroup$

Here is another method that I hope will be instructive.

Sum[i, {i, c}]

{9, 9, 9, 9}

In TraditionalForm:

Mathematica graphics

$\endgroup$

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.