# insert elements into 2 D array [duplicate]

say I have a 2 dimensionsal array like

a={{1,2,3},{4,5,6},{7,8,9}}


and a vector like

v={10,11,12}


I want the result to be

{{{10,1},{10,2},{10,3}},{{11,4},{11,5},{11,6}},{{12,7},{12,8},{12,9}}}


What command should I use? Thank you for suggestions. regards, hal.

## 4 Answers

There is probably a better solution, but this should work.

Example:

a={{1,2,3},{4,5,6},{7,8,9}}
v={10,11,12}

Thread[List[v[[#]], a[[#]]]] & /@ Range @ Length @ v


Alternative:

MapThread[Thread[{##}] &, {v, a}]


Output:

(*{{{10, 1}, {10, 2}, {10, 3}}, {{11, 4}, {11, 5}, {11, 6}}, {{12,
7}, {12, 8}, {12, 9}}}*)


Here's a quick way to get there,

Thread /@ Transpose@{v, a}

(* {{{10, 1}, {10, 2}, {10, 3}}, {{11, 4}, {11, 5}, {11,
6}}, {{12, 7}, {12, 8}, {12, 9}}} *)


The point here is that Transpose@{v, a} gives {{10, {1, 2, 3}}, {11, {4, 5, 6}}, {12, {7, 8, 9}}}, and you can use Thread on the individual elements.

You can achieve the desired result in many ways with Mathematica. Just some variants in addition:

MapThread[Thread[{##}] &, {v, a}]
Inner[Thread[{#1, #2}] &, v, a, List]
g[x_, y_] := Prepend[{#}, y] & /@ x;
h[x_, y_] := {y, #} & /@ x;
t = Thread[{a, v}];
g @@@ t
h @@@ t

MapThread[Map[t \[Function] {#1, t}, #2] &, {v, a}]

• thank you, also for pointing out the relation to similar post about MapThread.
– Hal
Apr 19, 2016 at 8:42