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

StackOverflow https://stackoverflow.com/questions/21865092

Question

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!

Was it helpful?

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

OTHER TIPS

matrix = [[None]*N for _ in xrange(M)]

Don't do [[None]*N]*M, or you'll get a list whose M elements are all really the same list object.

Note that this isn't really a matrix; it's a list of lists. Trying to do something like max(matrix) won't work right, and if you ever try to make the elements of your matrix be lists, it won't be possible to distinguish whether your data structure is supposed to be a matrix of lists, a list of matrices, or a 3D matrix. If you want to do a lot of matrix operations, NumPy is highly recommended. It offers actual matrices and arbitrary-dimension arrays with high performance and very convenient syntax.

matrix = []
for i in xrange(M):
    matrix.append([None]*N)

Numpy has an empty ndarray creation method

numpy.empty(shape, dtype, order)

for matrices matlib.empty:

numpy.matlib.empty(shape, dtype, order)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top