tw-S
tw-S

Reputation: 1217

Generate binary matrix with specific number of ones in row

EDIT: I also must have the sum of each column to equal a specific number!!

I want to generate a binary NxN matrix such that each row contains a specific number of 1's without repeating rows. Example: Generate 4x4 matrix with 2 ones in each row and with the sum of the column value equals 2, that is, generate

enter image description here

Hence, each row is unique and has exactly 2 ones and the sum of each column is 2. A WRONG answer would be:

B =

 1     1     0     0
 1     0     1     0
 1     0     0     1
 0     1     1     0

because the sum of column 1 does not equal 2 (but 3) and the sum of column 4 does not equal 2 (but 1). Each column should add up to 2. How can I achieve the correct answer in matlab?

Upvotes: 1

Views: 801

Answers (1)

sslloo
sslloo

Reputation: 521

You can try to generate a matrix with random permutations of a list p = randperm(n,k) https://fr.mathworks.com/help/matlab/ref/randperm.html?requestedDomain=www.mathworks.com

And generate a matrix from this rows (at list with a loop)

Upvotes: 1

Related Questions