matlab – Initialize empty matrix in Python

matlab – Initialize empty matrix in Python

If you are using `numpy` arrays, you initialize to 0, by specifying the expected matrix size:

``````import numpy as np
d = np.zeros((2,3))

>>> d
[[ 0.  0.  0.]
[ 0.  0.  0.]]
``````

This would be the equivalent of MATLAB s:

``````d = zeros(2,3);
``````

You can also initialize an empty array, again using the expected dimensions/size

``````d = np.empty((2,3))
``````

If you are not using numpy, the closest somewhat equivalent to MATLABs `d = []` (i.e., a zero-size matrix) would be using an empty list and then

append values (for filling a vector)

``````d = []
d.append(0)
d.append(1)
>>> d
[0, 1]
``````

or append lists (for filling a matrix row or column):

``````d = []
d.append(range(0,2))
d.append(range(2,4))
>>> d
[[0, 1], [2, 3]]
``````

You could use a nested list comprehension:

``````# size of matrix n x m
matrix = [ [ 0 for i in range(n) ] for j in range(m) ]
``````

matlab – Initialize empty matrix in Python

What about initializing a list, populating it, then converting to an array.

``````demod4 = []
``````

Or, you could just populate at initialization using a list comprehension

``````demod4 = [[func(i, j) for j in range(M)] for i in range(N)]
``````

Or, you could initialize an array of all zeros if you know the size of the array ahead of time.

``````demod4 = [[0 for j in range(M)] for i in range(N)]
``````

or

``````demod4 = [[0 for i in range(M)]*N]
``````

Or try using `numpy`.

``````import numpy as np

N, M = 100, 5000
np.zeros((N, M))
``````