MATLAB: Row / column summation constraints in random binary matrix.

matrixmatrix array

I want to generate a random binary matrix A(m, n) that meets two conditions:
  1. The summation of each column in A is 1.
  2. The summation of each row in A is less than a value in vector B={B1,…,Bm}, where B is a set of values.
Anyone knows, how can I implement it in MATLAB?
Thanks.

Best Answer

Here's one way, just using brute force try-and-see:
rows = 5;
columns = 11;
% Get some random B value, since we don't know what else to use.
B = randi(rows, rows, 1)
loopcounter = 1; % The failsafe.
maxAttempts = 100000; % A hundred thousand attempts.
while loopcounter < maxAttempts
A = zeros(rows, columns);
% Get rows to put 1's into
rowsWith1s = randi(rows, 1, columns);
% Load those 1s into A.
for col = 1 : columns
A(rowsWith1s(col), col) = 1;
end
% A % Print to command window
% Get row sums:
rowSums = sum(A, 2);
% Bail out if all sums are less than B
if all(rowSums < B)
fprintf('Succeeded after %d attempts\n', loopcounter);
break;
end
loopcounter = loopcounter + 1;
end
if loopcounter == maxAttempts
fprintf('Was not able to succeed after %d attempts.\n', loopcounter);
else
fprintf('The final A:\n');
rowSums % Print to command window

A % Print to command window
end