2

I have a square numpy 2D matrix.

2 2 2 2
2 2 2 2
2 2 2 2
2 2 2 2

And I need to set a certain count of random matrix values to 0. Let's say it is 5 elements. That means any 5 from 16 matrix values must be set to 0. For example new matrix could be

2 2 0 0
0 2 2 2
2 2 2 2
0 2 0 2

or

2 0 2 2
2 2 0 2
2 2 0 2
0 2 2 0

or some else.

How could I do this efficient way?

Pavel Antspovich
  • 1,111
  • 1
  • 11
  • 27

2 Answers2

5

This will do it:

import random
arr1d = arr.ravel()
randidx = random.sample(range(len(arr1d)), 5)
arr1d[randidx] = 0

This modifies arr because ravel() returns a view, not a copy.

For more on how the random numbers can be generated, see: Non-repetitive random number in numpy

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
-1

lets say your matrix is "matrix"

import random
for i in range(5):
    random1=random.randint(0,size_x_ofmatrix)
    random2=random.randint(0,size_y_ofmatrix)
    matrix[random1,random2]=0
mtpelerin
  • 9
  • 3