6

I have two ranges of values, one from 0 to 20 and the other from 0 to 80. I want to combine these into a list of "all possible" {x, y} coordinates that I can then plot later on. So the final list of points would be ~1700 long, consisting of:

{{0,0}, {0,1}, {0,2},..., {0,80}, {1,0}, {1,2}, {1,3},..., {1,80}, {2,0},..., {20, 80}}

I've seen things like Riffle and Partition thrown around but they're not quite what I'm looking for I think.

Artes
  • 57,212
  • 12
  • 157
  • 245
SixtySuit
  • 163
  • 1
  • 6

3 Answers3

11

The best aproach uses Tuples :

Tuples[{Range[0, 80], Range[0, 20]}] // Short 
{{0, 0}, {0, 1}, {0, 2}, {0, 3}, <<1693>>, {80, 17}, {80, 18}, {80, 19}, {80, 20}}

or a bit more briefly :

Tuples[ Range @@@ {{0, 80}, {0, 20}}]

Array provides a different way :

Sequence @@@ Array[{#1, #2} &, {81, 21}, 0]
Artes
  • 57,212
  • 12
  • 157
  • 245
  • Haha, I seriously just figured it the second before I hit refresh to see if there were any responses before I deleted this. And that's exactly what I typed! Thanks anyway. :P – SixtySuit Dec 07 '12 at 02:46
  • @SixtySuit Oh, really ? Take this comparison into account : http://mathematica.stackexchange.com/questions/4748/interlacing-a-single-number-into-a-long-list/4751#4751 – Artes Dec 07 '12 at 09:42
  • 1
    One can simplify the last method a little: Sequence @@@ Array[ List , {81, 21}, 0] – evanb Nov 23 '16 at 14:04
7

A more general function is Outer

 tuples = Outer[ List, Range[0, 80], Range[0, 20]]

Depending on how you want to use it you might want to Flatten the output

 Flatten[ tuples, 1]
Artes
  • 57,212
  • 12
  • 157
  • 245
bill s
  • 68,936
  • 4
  • 101
  • 191
7

Shorter versions of Artes' methods:

Tuples @ Range[0, {80, 20}]

Join @@ Array[List, {81, 21}, 0]

Related methods that may be of use:

a = {1, 2, 3, 4};
b = {q, r, s};

Distribute[{a, b}, List]
{{1, q}, {1, r}, {1, s}, {2, q}, {2, r}, {2, s}, {3, q},
 {3, r}, {3, s}, {4, q}, {4, r}, {4, s}}
Inner[f, List /@ a, {b}, g]
{{g[f[1, q]], g[f[1, r]], g[f[1, s]]}, {g[f[2, q]], g[f[2, r]], 
  g[f[2, s]]}, {g[f[3, q]], g[f[3, r]], g[f[3, s]]}, {g[f[4, q]], 
  g[f[4, r]], g[f[4, s]]}}
Outer[f, a, b]
{{f[1, q], f[1, r], f[1, s]}, {f[2, q], f[2, r], f[2, s]}, {f[3, q], 
  f[3, r], f[3, s]}, {f[4, q], f[4, r], f[4, s]}}

Notice the different levels preserved and opportunities to apply custom functions in each case. All methods shown have a place.

Also be familiar with the syntax of Table which is closely related to Do, Sum, Product, etc.

Table[{i, j}, {i, a}, {j, b}]
{{{1, q}, {1, r}, {1, s}}, {{2, q}, {2, r}, {2, s}}, {{3, q},
  {3, r}, {3, s}}, {{4, q}, {4, r}, {4, s}}}
Product[i + j, {i, a}, {j, b}]
(1 + q) (2 + q) (3 + q) (4 + q) (1 + r) (2 + r) (3 + r) (4 + r) (1 + s) (2 + s) (3 + s) (4 + s)

Also related is:

KroneckerProduct[a, b]
{{q, r, s}, {2 q, 2 r, 2 s}, {3 q, 3 r, 3 s}, {4 q, 4 r, 4 s}}
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371