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$
8
  • $\begingroup$ You can use Part to get the elements from the list, then Total to sum them up. $\endgroup$ Commented Oct 30, 2012 at 9:44
  • 14
    $\begingroup$ $3+3+1\neq 10\phantom{}$ $\endgroup$ Commented Oct 30, 2012 at 9:57
  • 1
    $\begingroup$ Plus @@@ (m\[Transpose]) will give you a list of the sums of the various elements of your list. $\endgroup$ Commented Oct 30, 2012 at 10:00
  • 4
    $\begingroup$ @J.M. which is why this is a tricky question ;-) $\endgroup$ Commented Oct 30, 2012 at 10:25
  • 6
    $\begingroup$ @J.M. base 7? :^) $\endgroup$ Commented Oct 30, 2012 at 10:56

5 Answers 5

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$
3
  • $\begingroup$ You can use these shortcuts if you don't like pressing Esc every time for Part brackets $\endgroup$ Commented Oct 30, 2012 at 14:27
  • $\begingroup$ Yes, I use it. I put in the post. Tks $\endgroup$ Commented Oct 30, 2012 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$ Commented Nov 13, 2015 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$
1
  • 1
    $\begingroup$ Total[m[[All , 2]]] works as well. :) $\endgroup$ Commented Oct 30, 2012 at 12:05
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$
1
  • $\begingroup$ {{1, 3}, {2, 3}, {4, 1}} // Query[Total, 2] // Trace // LeafCount results in 697 as of May 2023. $\endgroup$ Commented May 12, 2023 at 7:30
0
$\begingroup$

Just For fun.

m = {{1, 3}, {2, 3}, {4, 1}}; Last[Total[m]] 
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.