Group Abstract Group Abstract

Message Boards Message Boards

2
|
6.4K Views
|
6 Replies
|
15 Total Likes
View groups...
Share
Share this post:

Improve this code that uses Nested MapThread and Map?

Posted 9 years ago

This code gives the result I need, but there must be a better way. Any ideas?

l1 = {1, 2, 3}

l2 = {{a1, b1, c1, d1}, {a2, b2, c2}, {a2, b2, c2}}

 Flatten[Module[{t},
  MapThread[(#2 /. t -> #1) &,
   {l1, Map[{t, #} &, l2, {2}]}
   ]
  ], 1
 ]

The result is: {{1, a1}, {1, b1}, {1, c1}, {1, d1}, {2, a2}, {2, b2}, {2, c2}, {3, a2}, {3, b2}, {3, c2}}

POSTED BY: Jeff Burns
6 Replies

I like

Catenate@MapThread[Thread@*List, {l1, l2}]
POSTED BY: Szabolcs Horvát
Posted 9 years ago

This is the fastest, but I am not sure how this part work "Thread@*List". Can someone help me break it down?

POSTED BY: Jeff Burns

@* is short for Composition. Thread@*List does the same as Sander's Thread[{#1,#2}].

POSTED BY: Szabolcs Horvát
Posted 9 years ago

Thanks. That clears it up. I tried searching for “@*” in the help, but it does not return any results. Knowing the name of the command helps.

POSTED BY: Jeff Burns

Other possibilities:

Flatten[Table[{l1[[i]], l2[[i, j]]}, {i, Length[l1]}, {j,Length[l2[[i]]]}], 1]
Table[{l1[[i]], l2[[i, j]]}, {i, Length[l1]}, {j,Length[l2[[i]]]}] // Catenate
Flatten[Diagonal@Outer[List, l1, l2], 1]
Catenate@Diagonal@Outer[List, l1, l2]

Many many possibilities, I give you two other ways:

Join @@ MapThread[Thread[{#1, #2}] &, {l1, l2}]
Transpose[{Join @@ MapThread[ConstantArray, {l1, Length /@ l2}], Join @@ l2}]

Depending on the types of data (all numerical, symbolic, mixed) one method will be faster than the other...

NB. Note that Flatten[...,1] is the same as Join @@ ... , but the latter is generally faster (or in the worst case, equal). I'm not sure how it compares to Catenate @ ... though, I have a feeling it is a more 'higher-level' function, and probably slower...

POSTED BY: Sander Huisman
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard