Home > Back-end >  Numpy - create a random array from the range (1-100)
Numpy - create a random array from the range (1-100)

Time:12-28

I've got a question saying that "Create a 8×8 array with random natural values from the range (1-100) on the diagonal, other values should be 0. Hint: You can use numpy's 'eye' function."

I know for random array in numpy I need to use the following code

P = np.random.rand(8,8) print(P)

But I don't know how I can choose the range for it. I read that I can use random.radiant but that one is not working (I am writing my code on databrick). I appreciate it if you can help me to figure out what needs to be done.

CodePudding user response:

This code will do exactly what you are asking for. first create zero matrix. then create random numbers. then put them in dioganals. using np functions will be fastest.

import numpy as np
a=np.zeros((8,8))
r=np.random.randint(1, 101, size=8)
np.fill_diagonal(a,r)

CodePudding user response:

I can think of two ways:

import numpy as np

N = 8
rand_vals = np.random.randint(1, 101, size=N)

# I would go with:
out = np.diag(rand_vals)

# If you insist on using eye:
out = np.eye(N) * rand_vals

You can use np.random.rand to simulate np.random.randint between 1-100 like so:

rand_vals = np.floor(np.random.rand(N) * 100)   1

CodePudding user response:

In R you can this as follows:

 mat_ <- matrix(sample(1:1e2, 64, replace = F),ncol = 8, nrow = 8)
 # upper and lower null triangular matrix except main diagonal
 mat_[lower.tri(mat_)] <- 0
 mat_[upper.tri(mat_)] <- 0
 mat_
  • Related