# 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)
Raghwan Chitranshu il 13 Gen 2019
Risposto: Bruno Luong il 13 Gen 2019
Hi All,
I want to create a random binary matrix with equal number of ones in each column and also equal number of ones in each row.
Appreciate if anyone have an idea to implement this in Matlab.
Thanks.
##### 3 CommentiMostra 1 commento meno recenteNascondi 1 commento meno recente
Stephen23 il 13 Gen 2019
Raghwan Chitranshu il 13 Gen 2019
@Madhan thanks for the comment .
Basically I am looking to construct a matrix with these conditions
1. no all 0 coulmns
2. every column contains an odd number of 1's
3. the number od 1's in each row of the matrix should be made equal or as close as possible to the average (total number of 1's in matrix divided by number of rows)
if you can help regarding this
Regards

Accedi per commentare.

### Risposte (2)

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
locs = find(cmask & rmask & L ~= 1); %implicit expansion used!
if isempty(locs)
fprintf('try %d boxed in at iteration %d\n', trynum, K);
failed = true;
break;
end
thisloc = locs( randi(length(locs)) );
L(thisloc) = 1;
end
if ~failed
fprintf('try %d worked\n', trynum);
display(L)
break;
end
end
if failed
fprintf('Did not succeed in %d tries. You could increase maxtries, but are you sure there is a way to succeed?\n', maxtries);
end
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.
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Bruno Luong il 13 Gen 2019
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!