Numpy: Assignment and Indexing as Matlab

后端 未结 3 1394
夕颜
夕颜 2021-01-13 13:36

Sometimes is useful to assign arrays with one index only. In Matlab this is straightforward:

M = zeros(4);
M(1:5:end) = 1
M =

   1   0   0   0
   0   1   0          


        
相关标签:
3条回答
  • 2021-01-13 14:04

    Another way using unravel_index

    >>> M = zeros((4,4));
    >>> M[unravel_index(arange(0,4*4,5),(4,4))]= 1
    >>> M
    array([[ 1.,  0.,  0.,  0.],
           [ 0.,  1.,  0.,  0.],
           [ 0.,  0.,  1.,  0.],
           [ 0.,  0.,  0.,  1.]])
    
    0 讨论(0)
  • 2021-01-13 14:07

    You could try numpy.ndarray.flat, which represents an iterator that you can use for reading and writing into the array.

    >>> M = zeros((4,4))
    >>> M.flat[::5] = 1
    >>> print(M)
    array([[ 1.,  0.,  0.,  0.],
           [ 0.,  1.,  0.,  0.],
           [ 0.,  0.,  1.,  0.],
           [ 0.,  0.,  0.,  1.]])
    

    Note that in numpy the slicing syntax is [start:stop_exclusive:step], as opposed to Matlab's (start:step:stop_inclusive).

    Based on sebergs comment it might be important to point out that Matlab stores matrices in column major, while numpy arrays are row major by default.

    >>> M = zeros((4,4))
    >>> M.flat[:4] = 1
    >>> print(M)
    array([[ 1.,  1.,  1.,  1.],
           [ 0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.]])
    

    To get Matlab-like indexing on the flattened array you will need to flatten the transposed array:

    >>> M = zeros((4,4))
    >>> M.T.flat[:4] = 1
    >>> print(M)
    array([[ 1.,  0.,  0.,  0.],
           [ 1.,  0.,  0.,  0.],
           [ 1.,  0.,  0.,  0.],
           [ 1.,  0.,  0.,  0.]])
    
    0 讨论(0)
  • 2021-01-13 14:10

    You could do this using list indices:

    M = np.zeros((4,4))
    M[range(4), range(4)] = 1
    print M
    # [[ 1.  0.  0.  0.]
    #  [ 0.  1.  0.  0.]
    #  [ 0.  0.  1.  0.]
    #  [ 0.  0.  0.  1.]]
    

    In this case you could also use np.identity(4)

    0 讨论(0)
提交回复
热议问题