1
$\begingroup$

I am trying to replace Table with more efficient wrapping functions like Map, Apply or their derivatives, like MapThread or @@@. The use of Table is a habit inherited from procedural programming, since it works as DO WHILE loops. I wonder if there is a systematic way to think about wrapping functions when the lists have more than two levels.

For example:

a1 = {{{1, 2, 3, 4}, {5, 6, 7, 8}}, {{9, 10, 11, 12}, {13, 14, 15, 16}}};
a2 = {{17, 18, 19, 20}, {21, 22, 23, 24}};

I want the output produced by

Table[Transpose[{a2[[k]], a1[[q, k]]}], {q, 2}, {k, 2}]

which results in

{{{{17, 1}, {18, 2}, {19, 3}, {20, 4}}, {{21, 5}, {22, 6}, {23, 
7}, {24, 8}}}, {{{17, 9}, {18, 10}, {19, 11}, {20, 12}}, {{21, 
13}, {22, 14}, {23, 15}, {24, 16}}}}

Can I get the same result without resorting to Table? With a combination of Map or Apply and other functions, perhaps? I have tried many combinations without success.

Thank you in advance

$\endgroup$

1 Answer 1

2
$\begingroup$

Also avoid Map when you can with Transpose:

Transpose[
 {
  ConstantArray[a2, Length[a1]],
  a1
  },
 {4, 1, 2, 3}
 ]

{{{{17, 1}, {18, 2}, {19, 3}, {20, 4}}, {{21, 5}, {22, 6}, {23, 7}, {24, 8}}}, {{{17, 9}, {18, 10}, {19, 11}, {20, 12}}, {{21, 13}, {22, 14}, {23, 15}, {24, 16}}}}

$\endgroup$
2
  • $\begingroup$ Thanks for the response. Do you mind clarifying the sequence {4,1,2,3}? Why not {3,4,1,2}?. I tested it and got a different result and I read about it in the documentation but I don't understand. $\endgroup$ Commented Aug 22, 2018 at 13:33
  • $\begingroup$ {4, 1, 2, 3} means that the 1st slot wants to be the 4th slot, 2nd slot wants to be 1st slot, 3rd slot wants to be 3rd and 4th slot wants to be 3rd. Actually, I tried all permutations of the form {*,*,*,3}. By comparing Dimensions, I knew alread that the last slot hast to move to the third one. $\endgroup$ Commented Aug 22, 2018 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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