Suppose I have a list of lists with different lengths, sorted from longest to shortest
myLists = Sort[Table[RandomReal[1, RandomInteger[50]], {25}], Length@#1 > Length@#2 &];
I would like to add up all the first elements, then all the second, and so on elements for each list that has the required number of elements.
For example if my lists are
{
{1,2,3},
{4,5},
{6}
}
Then I want to return
{11,7,3}
The following code performs this using For loops, but I am trying to figure out a better way of doing this.
sums = Table[0, {Max[Length /@ a]}];
(* For each row element up to the length of the longest list *)
For[j = 1, j <= Max[ Length /@ a], j++,
(* For each list *)
For[k = 1, k <= Length[a], k++,
(* Add the element to the correct sum if it exists *)
If[Length[a[[k]]] >= j,
sums[[j]] = sums[[j]] + a[[k, j]],
Break[]
]
]
]
0
and then add? Or are zeros appropriate values that can exist in your ragged length list? $\endgroup$Flatten
to transpose a 'ragged' array. For exampleTotal /@ Flatten[list, {2}]
=> {11, 7, 3} $\endgroup$