Defex
Defex

Reputation: 137

How to insert (change values) matrix in matrix? Python (numpy)

For example, I have a matrix:

[ [1 2 3 4 5],

  [6 7 8 9 10],

  [11 12 13 14 15],

  [16 17 18 19 20],

  [21 22 23 24 25] ]

I want to insert [ [-1 -1 -1], [0 5 0] ] in some position, like:

[ [1 2 3 4 5],

  [6 7 8 9 10],

  [11 -1 -1 -1 15],

  [16 0 5 0 20],

  [21 22 23 24 25] ]

Upvotes: 0

Views: 7938

Answers (3)

David K
David K

Reputation: 3132

Based on the example, I would say you are trying to replace or modify part of the existing array rather than insert an array.

You could use basic slicing to get a view of the part of the array you want to overwrite, and assign the value of that slice to a new matrix of the same size as the slice. For example:

>>> x=np.matrix([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
>>> x
matrix([[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12],
        [13, 14, 15, 16]])
>>> x[1:3,1:4]=np.matrix([[-1,-2,-3],[-4,-5,-6]])
>>> x
matrix([[ 1,  2,  3,  4],
        [ 5, -1, -2, -3],
        [ 9, -4, -5, -6],
        [13, 14, 15, 16]])

In general, to describe a submatrix of m rows and n columns with its upper left corner at row r and column c of the original matrix, index the slice as x[r:r+m,c:c+n].

Upvotes: 1

Boyang Li
Boyang Li

Reputation: 157

This method take the matrix m, and replace the elements with array n starting from row r, column c

def replace(m, n, r, c):
    i = 0
    if len(n) + c > len(m[r]):
        return
    for each in n:
        m[r][c] = n[i]
        c += 1
        i += 1

you have to check the index boundaries for the matrix

Upvotes: 0

Rasmus
Rasmus

Reputation: 77

Use numpy insert! Here is an example from the numpy reference at scipy:

>>> a = np.array([[1, 1], [2, 2], [3, 3]])
>>> a
array([[1, 1],
       [2, 2],
       [3, 3]])
>>> np.insert(a, 1, 5)
array([1, 5, 1, 2, 2, 3, 3])
>>> np.insert(a, 1, 5, axis=1)
array([[1, 5, 1],
       [2, 5, 2],
       [3, 5, 3]]

Read more here: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.insert.html

Upvotes: 2

Related Questions