MATLAB: Specified number of ones in the matrix (column and row)

MATLABmatrixrandom number generatorsum

Hi. I need to create a square matrix filled with random values of 1 and 0. Sum of each row and each column must be equal to the given condition. e.g. matrix: 5×5 ; sum of 1's: 3

Best Answer

I couldn't figure out how to generate k permutations that are not redundant beside test and discard until it meets the condition (technique that I really hate to use). So here is the code that does what you want but I'm far from proud of it:
n = 10; % Matrix dimension
k = 4; % row/column sum target of 1s
l = min(k,n-k);
J = zeros(n,l);
for i=1:l
while true
J(:,i) = randperm(n);
if all(all(J(:,i)-J(:,1:i-1)~=0,2),1)
break
end
end
end
I = repmat((1:n)',1,l);
A = accumarray([I(:) J(:)],1,[n n]);
if l < k
A = 1-A;
end
sum(A,1)
sum(A,2)