Search code examples
pythonnumpymatrixrandom

randomly generate a matrix with fixed number of non zero values using python


I want to generate a random matrix (min value=0, max value=25, steps=5) with N rows and 6 columns, where the number of non-zero values (k) given as input.

Example:

Input: N=2 K=8

Output (result): [[ 5, 0, 20, 0, 15, 25], [ 0, 15, 15, 0, 25, 10]]

I tried to generate the matrix with the code: np.random.choice(np.arange(0,20, 5), size=(2, 6)) but I can't controll the number of non-zero value.


Solution

  • This code will generate an array of the shape you want with non-zero values everywhere, then it will insert the right amount of zeroes at random places.

    def generate_matrix(N, K):
        arr = np.random.choice( np.arange(5,26,5), size=(N,6))
        # inputs 6*N-K zeroes at random (unique) places
        np.put(arr, np.random.choice(arr.size, size=arr.size-K, replace=False), 0)
        return arr.tolist()