Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

looking for a random matrix of zeros and ones in python with a limited amount of ones

I am generating a matrix of zeros and ones in python as

poblacionCandidata = np.random.randint(0, 2, size=(4, 2))

However, I need for it to be only two ones at most in each row.

I have checked this question, but it is too complex for me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can anyone help me with this

The result should be something like

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

Best regards

>Solution :

You could just use a loop:

import numpy as np

def generate_matrix(rows: int, cols: int, max_ones_per_row: int) -> np.ndarray:
    """
    Generate a matrix with up to a specified number of ones per row.
    
    :param rows: The number of rows in the matrix.
    :param cols: The number of columns in the matrix.
    :param max_ones_per_row: The maximum number of ones to be placed in each row.
    :return: A numpy array representing the generated matrix.
    """
    matrix = np.zeros((rows, cols), dtype=int)
    for i in range(rows):
        ones_per_row = np.random.randint(0, max_ones_per_row + 1)
        ones_indices = np.random.choice(cols, ones_per_row, replace=False)
        matrix[i, ones_indices] = 1
    return matrix

poblacionCandidata = generate_matrix(rows=4, cols=4, max_ones_per_row=2)
print(poblacionCandidata)

Example Output:

[[1 0 0 0]
 [0 0 1 1]
 [0 0 0 0]
 [0 1 0 0]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading