Search code examples
pythonpython-3.xmatrix

Function to create matrix of zeros and ones, with a certain density of ones


I would like to create a function that takes three arguments (n,m,d) and it should output a matrix with n rows and m columns. The matrix should be populated with values 0 and 1 at random, in order to ensure that you have a density d of ones.

This is what I have come up with so far, just can't seem to work out how to integrate the density variable.

def create_matrix(n, m):
    count = 1
    grid = []
    while count <= n:
        for i in range(m):
            
            x = [random.randrange(0,2) for _ in range(m)]
            grid.append(x)

            count += 1

    return grid

Solution

  • import random
    def create_matrix(n, m, d):
    
        # if d is greater than multiple of n and m, return error
        if d > n*m : return f'd should be less than {n*m}'
        
        else:
            i = 0
            
            # Create a n x m matrix with all value being zero 
            mtrx = [[0 for x in range(m)] for y in range(n)]
            
            # Create a while loop with condtion i is less than d
            while i < d:
    
                # rest understandable with code
                r =  random.choice(range(n))
                c =  random.choice(range(m))
                
                
                if mtrx[r][c] != 1: mtrx[r][c] = 1
                else: i = i -1
                i += 1
        return mtrx
    
    r = create_matrix(4,5, 10)
    print(r)