'How to replace values in a matrix based on specific indices? [duplicate]

I'm trying to index a matrix based on an array of coordinates, so that I can replace the values in those positions with 1, and leave the rest as is. Here's what I mean:

I have the following 3x3 matrix

matrix = np.zeros((3,3), dtype=int)
matrix

>>> array([[0, 0, 0],
           [0, 0, 0],
           [0, 0, 0]])

and I have the following array

coords = np.array([[0,0],[2,1],[0,2]])
coords

>>> array([[0, 0],
           [2, 1],
           [0, 2]])

What I would like to do is replace the values in the original matrix with 1 only in the positions specified by the elements in the array coords. This is the desired output:

>>> array([[1, 0, 1],
           [0, 0, 0],
           [0, 1, 0]])

What I've tried to do is

matrix[coords]=1

However, this is the output I get:

>>> array([[1, 1, 1],
           [1, 1, 1],
           [1, 1, 1]])

Does anyone know how I can replace only the values in the positions specified, and obtain my desired output instead?

Thank you all for your help.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source