5
$\begingroup$

How can I add the elements in the sublists?
For example, if I have the list which is

 m={{1,3},{2,3},{4,1}}

then, the output that I want is 3+3+1=10. How can I do this?

$\endgroup$
  • $\begingroup$ You can use Part to get the elements from the list, then Total to sum them up. $\endgroup$ – b.gates.you.know.what Oct 30 '12 at 9:44
  • 13
    $\begingroup$ $3+3+1\neq 10\phantom{}$ $\endgroup$ – J. M. will be back soon Oct 30 '12 at 9:57
  • 1
    $\begingroup$ Plus @@@ (m\[Transpose]) will give you a list of the sums of the various elements of your list. $\endgroup$ – image_doctor Oct 30 '12 at 10:00
  • 4
    $\begingroup$ @J.M. which is why this is a tricky question ;-) $\endgroup$ – chris Oct 30 '12 at 10:25
  • 6
    $\begingroup$ @J.M. base 7? :^) $\endgroup$ – Mr.Wizard Oct 30 '12 at 10:56
4
$\begingroup$

I thinks the cleanest way is:

Total@m[[All, 2]]

using Esc[[Esc and Esc]]Esc.

If you use it a lot (like me), you can create shortcuts as explained here.

$\endgroup$
  • $\begingroup$ You can use these shortcuts if you don't like pressing Esc every time for Part brackets $\endgroup$ – rm -rf Oct 30 '12 at 14:27
  • $\begingroup$ Yes, I use it. I put in the post. Tks $\endgroup$ – Murta Oct 30 '12 at 18:46
  • $\begingroup$ @Murta, I asked the Q on [[ ]] but find all the answers a pain. Can you make a palette button or single front-end command? $\endgroup$ – alancalvitti Nov 13 '15 at 17:29
1
$\begingroup$

Following @b.gatessucks

 Total[m[[;; , 2]]]

  (* 7 *)

If you want to sum all components (as @image_doctor pointed out too, sorry I missed that)

 Plus @@@ Transpose[m]

 (* 7 7 *)
$\endgroup$
0
$\begingroup$
Last@Total[{{1, 3}, {2, 3}, {4, 1}}]

or

Total[{{1, 3}, {2, 3}, {4, 1}}]

for both components

$\endgroup$
0
$\begingroup$
 {{1, 3}, {2, 3}, {4, 1}} // Query[Total, 2]

7

Unfortunately the current Query and associated Dataset implementation is riddled with workarounds - this is going to tech support >>

{{1, 3}, {2, 3}, {4, 1}} // Query[Total, 2] // Trace // LeafCount

3175

Anyone interested in a timing study?

$\endgroup$
0
$\begingroup$

Just For fun.

m = {{1, 3}, {2, 3}, {4, 1}}; Last[Total[m]]
$\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.