Replace sub part of matrix by another small matrix in numpy

后端 未结 4 884
借酒劲吻你
借酒劲吻你 2020-12-03 21:05

I am new to Numpy and want to replace part of a matrix. For example, I have two matrices, A, B generated by numpy

In [333]: A = ones((5,5))

In [334]: A
Out[         


        
4条回答
  •  我在风中等你
    2020-12-03 21:13

    The following function replaces an arbitrary non-contiguous part of the matrix with another matrix.

    def replace_submatrix(mat, ind1, ind2, mat_replace):
      for i, index in enumerate(ind1):
        mat[index, ind2] = mat_replace[i, :]
      return mat
    

    Now an example of the application. We replace indices [1, 3] x [0, 3] (i.e. ind1 x ind2) of the empty 4 x 4 array x with the 2 x 2 array y of 4 different values:

    x = np.full((4, 4), 0)
    x
    array([[0, 0, 0, 0],
           [0, 0, 0, 0],
           [0, 0, 0, 0],
           [0, 0, 0, 0]])
    
    y = np.array([[1, 2], [5, 9]])
    y
    array([[1, 2],
           [5, 9]])
    
    ind1 = [1, 3]
    ind2 = [0, 3]
    res = replace_submatrix(x, ind1, ind2, y)  
    res  
    array([[0, 0, 0, 0],
           [1, 0, 0, 2],
           [0, 0, 0, 0],
           [5, 0, 0, 9]])
    

提交回复
热议问题