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

73 views Asked by At

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
3

There are 3 answers

5
Suramuthu R On BEST ANSWER
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)
0
d.b On
import random


def foo(row, col, d):
    N = row * col
    inds = set(random.sample(range(N), d))
    arr = [1 if i in inds else 0 for i in range(N)]
    return [arr[i:(i + col)] for i in range(0, N, col)]
    
foo(4, 5, 7)
# [[1, 0, 0, 0, 0], [0, 0, 1, 0, 1], [0, 1, 0, 0, 0], [0, 1, 1, 1, 0]]
0
TheHungryCub On
import random

def create_matrix(n, m, d):
    total_elements = n * m
    total_ones = int(total_elements * d)
    matrix = [[0] * m for _ in range(n)]

    ones_indices = random.sample(range(total_elements), total_ones)

    for idx in ones_indices:
        row = idx // m
        col = idx % m
        matrix[row][col] = 1

    return matrix

# Example usage:
n = 3
m = 5
d = 0.3 

result = create_matrix(n, m, d)
for row in result:
    print(row)

Output:

[0, 0, 0, 0, 0]
[0, 0, 0, 1, 0]
[0, 0, 1, 1, 1]

Note: If you provide d=0, there are no ones and if d=1 the elements are all ones.