Search code examples
pythonvectormatrixdimension

How to create a void matrix (not filled with ones or zeros) in Python of expected dimensions M times N?


In order to create a void vector a of N elements in Python we use:

a = [None] * N

How about creating a matrix of M times N not filled with ones or zeros? thank you!


Solution

  • a more "matrixy" answer is to use numpy's object dtype: for example:

    >>> import numpy as np
    >>> np.ndarray(shape=(5,6), dtype=np.object)
    array([[None, None, None, None, None, None],
           [None, None, None, None, None, None],
           [None, None, None, None, None, None],
           [None, None, None, None, None, None],
           [None, None, None, None, None, None]], dtype=object)
    

    But, as wim suggests, this might be inefficient, if you're using this to do math.

    >>> mat = np.empty(shape=(5,6))
    >>> mat.fill(np.nan)
    >>> mat
    array([[ nan,  nan,  nan,  nan,  nan,  nan],
           [ nan,  nan,  nan,  nan,  nan,  nan],
           [ nan,  nan,  nan,  nan,  nan,  nan],
           [ nan,  nan,  nan,  nan,  nan,  nan],
           [ nan,  nan,  nan,  nan,  nan,  nan]])
    >>>
    

    If you're really using more python objecty things, and don't intend to fill the matrix, you can use something nicer; a dict!

    >>> from collections import defaultdict
    >>> mat = defaultdict(lambda: None)
    >>> mat[4,4]
    >>> mat[4,4] is None
    True