0

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.

Hal
  • 1

4 Answers4

2

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}}}*)
e.doroskevic
  • 5,959
  • 1
  • 13
  • 32
2

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.

Jason B.
  • 68,381
  • 3
  • 139
  • 286
2

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
ubpdqn
  • 60,617
  • 3
  • 59
  • 148
2
MapThread[Map[t \[Function] {#1, t}, #2] &, {v, a}]
Chris Degnen
  • 30,927
  • 2
  • 54
  • 108