-1

I want to create a list of all possible (x,y) values.

For example - for input (x=2,y=3) the output should be:

np.array([
[0,0],
[0,1],
[0,2],
[1,0],
[1,1],
[1,2]])

The order doesn't really matter

user972014
  • 3,296
  • 6
  • 49
  • 89

2 Answers2

6

Quick and dirty:

>>> np.argwhere(np.ones((2, 3)))
array([[0, 0],
       [0, 1],
       [0, 2],
       [1, 0],
       [1, 1],
       [1, 2]])
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
  • I don't care about the upvotes, but I finally 1UP'd you on an answer ;) – cs95 May 29 '18 at 09:06
  • And coversely I am relishing the success of my populist answer ;-) – Paul Panzer May 29 '18 at 09:15
  • Meh. By the way, I don't think this is a duplicate. – cs95 May 29 '18 at 09:16
  • Certainly not the best links with that. – Paul Panzer May 29 '18 at 09:20
  • 1
    This question is pretty much a duplicate but I couldn't find exactly the same duplicate. However, the answer of this question can be found within target questions's answers. Please add the questions to the list if you found a more accurate one. Also a much faster approach for this solution (specially fir larger arrays) could be `np.dstack(np.indices((2, 3))).reshape(6, 2)`. – Mazdak May 29 '18 at 09:36
4

Inspired by Divakar's indices_merged_arr, this should be fast.

def indices_for(m, n):
    i, j = np.ogrid[:m, :n]
    v = np.empty((m, n, 2), dtype=np.uint32)
    v[..., 0] = i
    v[..., 1] = j
    v.shape = (-1, 2)

    return v

>>> indices_for(3, 2)
array([[0, 0],
       [0, 1],
       [0, 2],
       [1, 0],
       [1, 1],
       [1, 2]])

m, n = 10000, 10000
%timeit indices_for(m, n)
607 ms ± 9.12 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit np.argwhere(np.ones((m, n)))
4.69 s ± 225 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
cs95
  • 379,657
  • 97
  • 704
  • 746
  • Now that you reopened a quation with no attempt please add a benchmark with `np.dstack(np.indices((m, n))).reshape(m*n, 2)` too :)). Nice attempt tho(+). – Mazdak May 29 '18 at 09:41
  • @Kasramvd not on my machine now so can't benchmark :( but I've tried something similar with hstack and np.indices (I am aware of the function) but it's performance severely left something to be desired. Anyway, I'll test it in the morning. I'm still not convinced of the closure but it definitely could be a dupe of something else... so let me know and I'll close it when I get my votes back (I'm all out for today). – cs95 May 29 '18 at 10:12
  • @Kasramvd wait, can you please try it for m,n=10000,10000 as in my answer? – cs95 May 29 '18 at 10:16
  • I was about to do that it the IPython raises memory error. This is problem with Ipyhton-3 that I always encounter to. – Mazdak May 29 '18 at 10:17
  • @Kasramvd what is your code doing that ours isn't? :P – cs95 May 29 '18 at 10:18
  • @I tried other snippets and my machine with 16 GB RAM went to halt!! :)) – Mazdak May 29 '18 at 10:24