pythonarraysnumpy

Explain this 4D numpy array indexing intuitively


x = np.random.randn(4, 3, 3, 2)
print(x[1,1])

output:
[[ 1.68158825 -0.03701415]
[ 1.0907524  -1.94530359]
[ 0.25659178  0.00475093]]

I am python newbie. I can't really understand 4-D array index like above. What does x[1,1] mean?

For example, for vector

a = [[2][3][8][9]], a[0] = 2, a[3] = 9. 

I get this but I don't know what x[1,1] refers to.

Please explain in detail. Thank you.


Solution

  • A 2D array is a matrix : an array of arrays.

    A 4D array is basically a matrix of matrices:

    matrix of matrices

    Specifying one index gives you an array of matrices:

    >>> x[1]
    array([[[-0.37387191, -0.19582887],
            [-2.88810217, -0.8249608 ],
            [-0.46763329,  1.18628611]],
    
           [[-1.52766397, -0.2922034 ],
            [ 0.27643125, -0.87816021],
            [-0.49936658,  0.84011388]],
    
           [[ 0.41885001,  0.16037164],
            [ 1.21510322,  0.01923682],
            [ 0.96039904, -0.22761806]]])
    

    enter image description here

    Specifying two indices gives you a matrix:

    >>> x[1, 1]
    array([[-1.52766397, -0.2922034 ],
           [ 0.27643125, -0.87816021],
           [-0.49936658,  0.84011388]])
    

    enter image description here

    Specifying three indices gives you an array:

    >>> x[1, 1, 1]
    array([ 0.27643125, -0.87816021])
    

    enter image description here

    Specifying four indices gives you a single element:

    >>> x[1, 1, 1, 1]
    -0.87816021212791107
    

    enter image description here

    x[1,1] gives you the small matrix that was saved in the 2nd column of the 2nd row of the large matrix.