7
$\begingroup$

I'm trying to write a function which will take multiple lists of function parameters and riffle all of their parameters together as input for a function. To be more explicit, consider if I had the following lists of parameters: P1={a1,a2,a3,...,an}, P2={b1,b2,b3,...,bn}.... I then want to write a function, say called riffleParams, that will do the following:

riffleParams[P1,P2,P3,...PN]={{a1,b1,c1,...},{a2,b1,c1,...},...}

Or in more concrete terms, you would have

riffleParams[{a,b},{1,2,3,4}]={{a,1},{b,1},{a,2},{b,2},{a,3},{b,3},{a,4},{b,4}}

I can think of some nasty ways to do this but extending it to arbitrary number of input parameter lists seems tricky. I figure there is probably a cleaner way to implement it that I'm not familiar with. Thanks for any assistance.

$\endgroup$
2
  • 1
    $\begingroup$ Tuples[] does a different arrangement: Tuples[{{a, b}, {1, 2, 3, 4}}]; nevertheless, maybe it is useful for you? $\endgroup$ Jan 27, 2020 at 2:26
  • $\begingroup$ Ah, that works fine! I knew there would be some built-in to do this... Not sure how to accept an answer from the comments, but thanks! $\endgroup$ Jan 27, 2020 at 2:28

2 Answers 2

9
$\begingroup$

As mentioned in the comments, Tuples[] does it:

Tuples[{{a, b}, {1, 2, 3, 4}}]
   {{a, 1}, {a, 2}, {a, 3}, {a, 4}, {b, 1}, {b, 2}, {b, 3}, {b, 4}}

Before Tuples[] became a built-in function, one used to use Outer[] for the task, in conjunction with Flatten[]:

Flatten[Outer[List, {a, b}, {1, 2, 3, 4}], 1]
$\endgroup$
7
$\begingroup$

There is also: Distribute

Distribute[{{a, b}, {1, 2, 3, 4}}, List]

{{a, 1}, {a, 2}, {a, 3}, {a, 4}, {b, 1}, {b, 2}, {b, 3}, {b, 4}}

$\endgroup$

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.