Initialize empty matrix in Python

前端 未结 7 1310
旧巷少年郎
旧巷少年郎 2020-12-31 07:56

I am trying to convert a MATLAB code in Python. I don\'t know how to initialize empty matrix in Python.

MATLAB Code:

demod4(1) = [];
<
7条回答
  •  春和景丽
    2020-12-31 08:33

    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 MATLAB's 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]]
    

    See also:

    initialize a numpy array (SO)

    NumPy array initialization (fill with identical values) (SO)

    How do I create an empty array/matrix in NumPy? (SO)

    NumPy for MATLAB users

提交回复
热议问题