2

I have a list of lists of numbers. I add them into one list by adding all of the first elements together, all of the second elements together, etc. For example, if my list were { {1,2,3}, {1,2,3}, {1,2,3,4} } I would want to end up with {3,6,9,4}. How do I do this in Mathematica?

Kate
  • 21
  • 2

3 Answers3

2
a = {{1, 2, 3}, {1, 2, 3}, {1, 2, 3, 4}};

Total@PadRight@a

{3, 6, 9, 4}

Chris Degnen
  • 8,443
  • 2
  • 23
  • 40
1

Among its many useful features, Flatten will transpose a 'ragged' array (see here for a nice explanation, or check out the 'applications' subsection of the documentation on Flatten)

Total /@ Flatten[#, {{2}}] &@{{1, 2, 3}, {1, 2, 3}, {1, 2, 3, 4}}

{3, 6, 9, 4}

Community
  • 1
  • 1
681234
  • 4,214
  • 2
  • 35
  • 42
0

If all the rows were the same length then adding the rows would do this.

So make all the rows the same length by appending zeros and then add them.

lists = {{1, 2, 3}, {1, 2, 3}, {1, 2, 3, 4}};
max = Max[Length /@ lists]; min = Min[Length /@ lists];
zeros = Table[0, {max - min}];
Plus @@ Map[Take[Join[#, zeros], max] &, lists]
Bill
  • 3,664
  • 1
  • 12
  • 9