Skip to content
Advertisement

Insert matrix inside another matrix using numpy without overwriting some original values

I need to insert a matrix inside another one using numpy

The matrix i need to insert is like this one:

tetraminos = [[0, 1, 0], 
              [1, 1, 1]]

While the other matrix is like this:

board = numpy.array([
    [6,0,0,0,0,0,0,0,0,0],
    [6,0,0,0,0,0,0,0,0,0]
])

The code i’m actually using this one:

board[0:0 + len(tetraminos), 0:0 + len(tetraminos[0])] = tetraminos

The problem matrix that i’m getting is this one:

wrong_matrix = numpy.array([
        [[0,1,0,0,0,0,0,0,0,0],
        [1,1,1,0,0,0,0,0,0,0]]
])

while the expected result is:

expected_result = numpy.array([
    [6,1,0,0,0,0,0,0,0,0],
    [1,1,1,0,0,0,0,0,0,0]
])

The error is that, since the matrix contains 0, when i insert it inside the new one i lost the first value in the first row (the number 6), while i wanted to keep it

Full code:

import numpy
if __name__ == '__main__':

    board = numpy.array([
        [6,0,0,0,0,0,0,0,0,0],
        [6,0,0,0,0,0,0,0,0,0]
    ])

    tetraminos = [[0, 1, 0], [1, 1, 1]]

    board[0:0 + len(tetraminos), 0:0 + len(tetraminos[0])] = tetraminos
    print(board)

    expected_result = numpy.array([
        [6,1,0,0,0,0,0,0,0,0],
        [1,1,1,0,0,0,0,0,0,0]
    ])

    exit(1)

Advertisement

Answer

As long as you always want to put a constant value in there, you can treat your tetramino as a mask and use the np.putmask function:

>>> board = np.array([[6,0,0,0,0,0,0,0,0],[6,0,0,0,0,0,0,0,0]])
>>> board
array([[6, 0, 0, 0, 0, 0, 0, 0, 0],
       [6, 0, 0, 0, 0, 0, 0, 0, 0]])
>>> tetraminos = [[0,1,0],[1,1,1]]
>>> np.putmask(board[0:len(tetraminos),0:len(tetraminos[0])], tetraminos,1)
>>> board
array([[6, 1, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 0, 0, 0, 0, 0, 0]])
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement