Random numbers on matrix diagonal (possible duplicate)

Viewed 111

Is it possible to amend this code, so that matrix diagonal would consist of different random numbers? For now they are the same:

    rand_m = np.eye(4, 4, k = 0, dtype=int)
    rand_m[rand_m == 1] = np.random.randint(1, 100)
    print(rand_m)

   [[44  0  0  0]
     [ 0 44  0  0]
     [ 0  0 44  0]
     [ 0  0  0 44]]
2 Answers

randint can be used to generate a random vector at once. np.diag is used to construct a matrix with that vector being the diagonal.

np.diag(np.random.randint(1,100,4))

Try setting the size argument of randint() to 4, like this:

rand_m = np.eye(4, 4, k = 0, dtype=int)
rand_m[rand_m == 1] = np.random.randint(1, 100, size=4)
Related