Clear Filters
Clear Filters

Creating binary matrix with at least q ones on each row

2 views (last 30 days)
I have a matrix which is intended to represent gender, so I want it to be roughly 0's and 1's. I am doing it as follows:
sex=round(rand(m,n));
The problems is that sometimes generates rows with only 0's or 1's. I want to change it so that it always contains at least q 1's and at most k 0's. Is there an easy way to do this?

Accepted Answer

Walter Roberson
Walter Roberson on 23 Oct 2016
temp = [ones(m,q), zeros(m,k), round(rand(m,n-k-q))];
Now you can randomize the order within each row of temp
[~, idx] = sort( rand(m,n), 2);
sex = temp(sub2ind(size(temp), ndgrid(1:m,1:n), idx));
However: neither sex nor gender are binary. There are over a dozen intersex conditions; the wider field is Disorders of Sexual Development; and see http://www.joshuakennon.com/the-six-common-biological-sexes-in-humans/. There at least 19 catalogued genders; New York City recognizes 31 gender identities

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!