Hello I need some help on how to add a list to a list of list. The program would have to do as below:
{{0,0}, {0}, {0,0,0}}+{1,2,3,4,5,6}
will give
{{1,2}, {3}, {4,5,6}}.
Could this be done? Any help is greatly appreciated. Thanks in advance.
Answer
Without testing whether there are as many elements in the first list as there are in the second, the solution is as simple as
listAdd[structured_, flat_] := Module[{i = 1},
Function[elm, elm + flat[[i++]], {Listable}][structured]
]
listAdd[{{a, b}, {c}, {d, e, f}}, {1, 2, 3, 4, 5, 6}]
(* {{1 + a, 2 + b}, {3 + c}, {4 + d, 5 + e, 6 + f}} *)
To understand why this works, please study carefully my answer of this question.
Comments
Post a Comment