0
$\begingroup$

This question already has an answer here:

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$

marked as duplicate by Kuba, Martin Ender, user9660, Jason B., xyz Apr 18 '16 at 9:38

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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$
  • $\begingroup$ +1 Thread[{##}] $\endgroup$ – Chris Degnen Apr 18 '16 at 9:53
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$
  • $\begingroup$ thank you, also for pointing out the relation to similar post about MapThread. $\endgroup$ – Hal Apr 19 '16 at 8:42

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