Using a numpy array to assign values to another array
<p>I have the following numpy array <code>matrix</code> ,</p>

<pre><code>matrix = np.zeros((3,5), dtype = int)

array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
</code></pre>

<p>Suppose I have this numpy array <code>indices</code> as well</p>

<pre><code>indices = np.array([[1,3], [2,4], [0,4]])

array([[1, 3],
       [2, 4],
       [0, 4]]) 
</code></pre>

<p><strong>Question:</strong> How can I assign <code>1</code>s to the elements in the <code>matrix</code> where their indices are specified by the <code>indices</code> array. A vectorized implementation is expected.</p>

<p>For more clarity, the output should look like:</p>

<pre><code>    array([[0, 1, 0, 1, 0], #[1,3] elements are changed
           [0, 0, 1, 0, 1], #[2,4] elements are changed
           [1, 0, 0, 0, 1]]) #[0,4] elements are changed
</code></pre>

<p>this involves loop and hence may not be very efficient for large arrays</p>

<pre><code>for i in range(len(indices)):
    matrix[i,indices[i]] = 1

&gt; matrix
 Out[73]: 
array([[0, 1, 0, 1, 0],
      [0, 0, 1, 0, 1],
      [1, 0, 0, 0, 1]])
</code></pre>

python arrays numpy indexing vectorization