Search code examples
pythonpython-3.xnumpymatrixtile

Unexpected collapse of dimension when calling np.tile()


I am creating a multi-dimension numpy matrix like this:

a = np.array([255, 0])                            
mins_and_maxes = np.tile(a, [9, 2, 43]) 

I'm expecting mins_and_maxes to be a 4-D array with a shape of (9, 2, 43, 2). However, mins_and_maxes has a shape of (9, 2, 86). The [255, 0] arrays are sort of being 'dissolved'. (I can't think of a better word. "Exploded"?)

How do I get a matrix of size (9, 2, 43) where every element is a copy of the array of length 2, [255, 0]?


Solution

  • You can try:

    a = np.array([255, 0])
    
    mins_and_maxes = np.tile(a, [9, 2, 43, 1])
    
    mins_and_maxes.shape
    #(9, 2, 43, 2)
    

    mins_and_maxes

    #array([[[[255,   0],
             [255,   0],
             [255,   0],
             ...,
             [255,   0],
             [255,   0],
             [255,   0]],
           [[[255,   0],
             [255,   0],
             [255,   0],
             ...,
             [255,   0],
             [255,   0],
             [255,   0]],
    
            [[255,   0],
             [255,   0],
             [255,   0],
             ...,
             [255,   0],
             [255,   0],
             [255,   0]]],
    
    
           [[[255,   0],
             [255,   0],
             [255,   0],
             ...,
             [255,   0],
             [255,   0],
             [255,   0]],
    
            [[255,   0],
             [255,   0],
             [255,   0],
             ...,
             [255,   0],
             [255,   0],
             [255,   0]]]])