Search code examples
pythonmatrixrandommax

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.

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