2
$\begingroup$

For example, I have data like this:

 m = {{1,2,3},{4,5,6}}

It means 1,2,3 are available x position, 4,5,6 are available y position. The question is, how to get all available points? In this case, all available points are {{1,4},{1,5},{1,6},{2,4},{2,5},{2,6},{3,4},{3,5},{3,6}}, but how can I write a general code to solve these problems, especially when dimension is much more than 2?

I found this problem is called Cartesian product. But I still have no idea how to solve it.

$\endgroup$
1
  • 4
    $\begingroup$ probably Tuples $\endgroup$
    – Kuba
    Jul 8, 2016 at 10:39

2 Answers 2

6
$\begingroup$

Tuples can be applied to a series of lists to give you each combination:

>> Tuples[{{1, 2, 3}, {4, 5, 6}}]

{{1, 4}, {1, 5}, {1, 6}, {2, 4}, {2, 5}, {2, 6}, {3, 4}, {3, 5}, {3, 6}}

and it works with arbitrarily many, and different sizes of lists:

>> Tuples[{{y, z}, {1, 2, 5}, {7}, {9, y}}]

{{y, 1, 7, 9}, {y, 1, 7, y}, {y, 2, 7, 9}, {y, 2, 7, y}, {y, 5, 7, 9}, {y, 5, 7, y}, {z, 1, 7, 9}, {z, 1, 7, y}, {z, 2, 7, 9}, {z, 2, 7, y}, {z, 5, 7, 9}, {z, 5, 7, y}}

>> Length[%]

12 (* 2 options for first coordinate, 3 for second, 1 for third, 2 for fourth. 2*3*1*2=12 *)
$\endgroup$
2
$\begingroup$
Outer[List, {1, 2, 3}, {4, 5, 6}, 1]

(* {{{1, 4}, {1, 5}, {1, 6}}, {{2, 4}, {2, 5}, {2, 6}}, {{3, 4}, {3, 5}, {3, 6}}} *)
$\endgroup$

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