j

How to reshape an array with an arbitrary size in one dimension?


How would you go about reshaping a length-N 1D array into an (N/2) x 2 array? In numpy, for example, you can use -1 in place of N/2 when reshaping:

>>> x = np.array([1,2,3,4])
>>> x.reshape((-1, 2))
array([[1, 2],
       [3, 4]])

So I'm wondering if there's a J equivalent. It feels clunky to explicitly calculate the required number of rows.


Solution

  • This is what infix (\) is for: n ,\y will ravel (,) every n items ("infixes" of length n). If n is negative the infixes are non overlapping.

    y =. i.20
    
    _2 ,\y
     0  1
     2  3
     4  5
     6  7
     8  9
    10 11
    12 13
    14 15
    16 17
    18 19
    
    _3 ,\y
     0  1  2
     3  4  5
     6  7  8
     9 10 11
    12 13 14
    15 16 17
    18 19  0