How to create a random binary matrix with equal number of ones in each column and equal number of 1 in each row ?

2 次查看(过去 30 天)
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 个评论
Raghwan Chitranshu
Raghwan Chitranshu 2019-1-13
@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

请先登录,再进行评论。

回答(2 个)

Walter Roberson
Walter Roberson 2019-1-13
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!
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.

Bruno Luong
Bruno Luong 2019-1-13

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by