Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

This question already has an answer here:

Let's say I have two lists, and I'd like to generate a "cartesian product" from these two. Specifically

Inputs:

A = {{{1}}, {{2}}, {{1}, {2}}};
B = {8, 9};

Desired output:

X = {{{{1}} -> 8, {{1}} -> 9}, {{{2}} -> 8, {{2}} -> 9}, {{{1}, {2}} -> 
   8, {{1}, {2}} -> 9}}

I tried

f[#1, #2]& /@ {A, B}

but it didn't work. I also tried to use Thread, but that didn't work either.

Edit

Outer doesn't really work either, since it goes to all the leaves and extracts them first.

Outer[#1 -> #2, A, B]

{{{{1 -> 8, 1 -> 9}}}, {{{2 -> 8, 2 -> 9}}}, {{{1 -> 8, 1 -> 9}}, {{2 -> 8, 2 -> 9}}}}

share|improve this question
1  
Have you seen the 3rd argument of Outer? Outer[Rule, A, B, 1] –  rm -rf Jul 3 '13 at 17:46
    
@rm-rf I have now! –  cartonn Jul 3 '13 at 17:47
    
and outer is much faster than my Table suggestion. –  bobthechemist Jul 3 '13 at 18:00
1  
People, surely this question is a duplicate. Please exert the effort to look for duplicates before answering; thanks. –  Mr.Wizard Jul 3 '13 at 18:11
    
This is a duplicate of the linked post with the only difference being that Rule is the function instead of Join. There are several answers there, most/all of which should be applicable here (cc @Mr.Wizard) –  rm -rf Jul 3 '13 at 19:50
add comment

marked as duplicate by rm -rf Jul 3 '13 at 19:48

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.

3 Answers

up vote 2 down vote accepted

You just need to apply the third argument of Outer as rm -rf suggested. With your A and B,

Outer[#1 -> #2 &, A, B, 1]

gives

{{{{1}} -> 8, {{1}} -> 9}, {{{2}} -> 8, {{2}} -> 9}, {{{1}, {2}} ->  8, {{1}, {2}} -> 9}}

as you requested. To check (with your X)

Outer[#1 -> #2 &, A, B, 1] == X

True
share|improve this answer
add comment

I may be misinterpreting, but is this what you are looking for ?

Outer[f, {a, b, c}, {1, 2, 3}]

(* {{f[a, 1], f[a, 2], f[a, 3]}, {f[b, 1], f[b, 2], 
  f[b, 3]}, {f[c, 1], f[c, 2], f[c, 3]}} *)
share|improve this answer
add comment

How about this:

A = {{{1}}, {{2}}, {{1}, {2}}};
B = {8, 9};
Table[{i -> j}, {i, A}, {j, B}]

which gives me:

{{{{{1}} -> 8}, {{{1}} -> 9}}, {{{{2}} -> 8}, {{{2}} -> 
    9}}, {{{{1}, {2}} -> 8}, {{{1}, {2}} -> 9}}}

I've got one too many sets of braces, it looks like.

share|improve this answer
    
Changing {i->j} to First@{i->j} gives the desired output I think. –  bobthechemist Jul 3 '13 at 17:51
add comment

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