0
$\begingroup$

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.

$\endgroup$
0

4 Answers 4

2
$\begingroup$

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}}}*)
$\endgroup$
0
2
$\begingroup$

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.

$\endgroup$
2
$\begingroup$

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
$\endgroup$
2
$\begingroup$
MapThread[Map[t \[Function] {#1, t}, #2] &, {v, a}]
$\endgroup$
1
  • $\begingroup$ thank you, also for pointing out the relation to similar post about MapThread. $\endgroup$
    – Hal
    Apr 19, 2016 at 8:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.