How to create a random binary matrix with equal number of ones in each column and equal number of 1 in each row ?
8 visualizzazioni (ultimi 30 giorni)
Walter Roberson il 13 Gen 2019
N = 10; %number of 1s to place
M = 20; %dimension of matrix
maxtries = 10; %random placement can fail. How often to retry ?
for trynum = 1 : maxtries
L = zeros(M,M);
failed = false;
for K = 1 : M*N
cmask = sum(L) < N;
rmask = sum(L,2) < N;
locs = find(cmask & rmask & L ~= 1); %implicit expansion used!
fprintf('try %d boxed in at iteration %d\n', trynum, K);
failed = true;
thisloc = locs( randi(length(locs)) );
L(thisloc) = 1;
fprintf('try %d worked\n', trynum);
fprintf('Did not succeed in %d tries. You could increase maxtries, but are you sure there is a way to succeed?\n', maxtries);
My tests show that with this particular combination, 10 of 20, that success rate in placing within 10 tries is roughly 50% -- suggesting that maxtries should perhaps be increased.