5

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?

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
Sungjin Lee
  • 171
  • 2

5 Answers5

4

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.

Murta
  • 26,275
  • 6
  • 76
  • 166
1

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 *)
chris
  • 22,860
  • 5
  • 60
  • 149
0
Last@Total[{{1, 3}, {2, 3}, {4, 1}}]

or

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

for both components

s0rce
  • 9,632
  • 4
  • 45
  • 78
0
 {{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?

alancalvitti
  • 15,143
  • 3
  • 27
  • 92
  • {{1, 3}, {2, 3}, {4, 1}} // Query[Total, 2] // Trace // LeafCount results in 697 as of May 2023. – Syed May 12 '23 at 07:30
0

Just For fun.

m = {{1, 3}, {2, 3}, {4, 1}}; Last[Total[m]]
Bob Brooks
  • 466
  • 2
  • 13