MATLAB: How can i create matrix of zeros and ones (randomly) sucj that the maximum sum of each row and coloumn =5

1matrixrandom matrixrandom matrix of (o

random matrix(0,1) with specific sum

Best Answer

Without knowing the size of your matrix, i.e, the number of unknown elements, this is anything from trivial to do, to very non-trivial, especially if you wish those elements to be uniformly distributed subject to that constraint.
As well, the constraint on both the row and column sums makes things less trivial.
Anyway, for a 5x5 matrix, the answer is trivial, rand(5,5).
For a 100x100 matrix, the answer is very different, and quite un-trivial.
So I'd need some information from you. What size is the matrix?
=======================
Edit: From the comments, we have learned that the matrix is to be 25x25, boolean, with row and column sums that may not exceed 5 for any row or column.
There are several schemes I can think of. The simplest is quite simple really.
A = rand(25,25) > 0.05;
A = triu(A,-2);
A = tril(A,2);
Lets see what this did. spy(A)
As you can see, I created a penta-diagonal array of mostly ones. The relative fraction of ones here is 95% by the way it was constructed, so that will affect the final distribution of ones in the end result.
The trick now is to use randperm.
A = A(randperm(25),randperm(25));
spy(A)
We can verify the distribution of row and column sums.
sum(A,1)
ans =
Columns 1 through 24
5 5 4 5 4 4 3 5 5 4 3 3 5 5 5 4 5 4 4 5 5 5 5 5
Column 25
5
sum(A,2)
ans =
5
4
5
5
5
4
5
5
4
5
5
5
3
5
5
4
5
5
3
4
3
4
5
4
5
As you can see, the row and column sums never exceed 5. The actual distribution of those sums will be determined by the initial random sample. If you wanted fewer ones, then use a larger value on the initial test, instead of 0.05.
If you are worried that the row or column sum can ever exceed 5, think about it. Think about what randperm does and how I transformed that penta-diagonal matrix. Since it starts out never exceeding the row or column sum limit, the permuted array also has the same property!
Related Question