pythonarraysmultidimensional-arraynumpy

Create arbitrary multidimensional zeros array


I need to make a multidimensional array of zeros.

For two (D=2) or three (D=3) dimensions, this is easy and I'd use:

a = numpy.zeros(shape=(n,n)) 

or

a = numpy.zeros(shape=(n,n,n))

How for I for higher D, make the array of length n?


Solution

  • You can multiply a tuple (n,) by the number of dimensions you want. e.g.:

    >>> import numpy as np
    >>> N=2
    >>> np.zeros((N,)*1)
    array([ 0.,  0.])
    >>> np.zeros((N,)*2)
    array([[ 0.,  0.],
           [ 0.,  0.]])
    >>> np.zeros((N,)*3)
    array([[[ 0.,  0.],
            [ 0.,  0.]],
    
           [[ 0.,  0.],
            [ 0.,  0.]]])