0

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 
1
  • 1
    Do you mean if d=0 there are no ones and if d=1 the elements are all ones? Commented Mar 31, 2024 at 18:16

3 Answers 3

2
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) 
Sign up to request clarification or add additional context in comments.

5 Comments

or if d is a floating point value 0.0 < d < 1.0, change the while loop to while i < (m*n*d).
yes, you can add more conditions
This is not adding conditions. I mean that it is unclear what the values of d will be from the question. Your interpretation is valid. I'm offering an alternative.
Do you mean to add if isinstance(d, float) and 0.0 < d < 1.0: d = d*100 after 2nd line?
no, I mean depending on the intended usage and values of d, you can change while i < d: to while i < (m*n*d). In fact, in that case, you can remove the if...else entirely.
1
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.

Comments

-1
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]] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.