# how to modify a numpy matrix element-wise

I am currently trying to iterate over a matrix and modifying the elements inside it following some logic.
I tried using the standard procedure for iterating matrices, but this only outputs the element at the current index, without updating the matrix itself.

This is what i have tried:

``````for row in initial_matrix:
for element in row:
if np.random.rand() > 0.5: element = 0
print(element)

print(initial_matrix)
``````

This, however, does not update `initial matrix`, I also tried:

``````for row in range(len(initial_matrix)):
for element in range(row):
if np.random.rand() > 0.5: initial_matrix[row, element] = 0
print(element)

print(initial_matrix)
``````

This is somehow working, but only in the lower diagonal of the matrix, while the upper remains unchanged.
Here is the output:

``````0
0
1
0
1
2
0
1
2
3
[[1. 1. 1. 1. 1.]
[0. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[0. 0. 1. 1. 1.]
[0. 1. 1. 0. 1.]]
``````

### >Solution :

Here’s a minimalist modification (UPDATED to use np.array throughout) to your code which will do what I believe you are asking:

``````import numpy as np
initial_matrix = np.array([
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]])
for row in range(len(initial_matrix)):
for element in range(len(initial_matrix[row])):
if np.random.rand() > 0.5:
initial_matrix[row, element] = 0
print(initial_matrix)
``````

Output:

``````[[0 1 1 1 0]
[1 1 1 0 0]
[0 0 0 0 0]
[0 1 1 0 0]
[1 0 0 1 0]]
``````

Here, I have assumed that you start with a matrix containing `1` in every position and that you want to change this to `0` where your `random()` criterion is met.

As you can see, an adjustment to the inner loop logic of your original code was helpful in getting this to work.