Construct a binary matrix so that each column contains only one "1", and the sum of each row has the desired value

I want to build a binary (0s and 1s) matrix that satisfies the following restrictions:

  • Each column should contain only one binary 1 and the remaining elements of this column: 0s.

  • The sum of each ROW matrix should be desired. For example, if a rowSum vector [5 7 6 8 .......] is given, then the sum of the first row should be 5, the sum of the second row should be 7, etc.

  • nCol == Sum(rowSum)

In addition, I would like to consider several (for example, 7) matrices satisfying the same conditions.

EDIT:
I tried to write code and fill in part of it. Code:

 x=rand(21,50,7); for k=1:7 cons=max(x(:,:,7)); for i=1:50 for j=1:21 if x(j,i,k)==cons(i) x(j,i,k)=1; else x(j,i,k)=0; end end end end x 
+4
source share
1 answer

It is not always possible to build a binary matrix that satisfies your requirements. Suppose you need a binary matrix of size nRows x nCols with rowSum (a vector of length nRows ) rowSum(k) number 1 in k th row. So, if nCol ~= sum( rowSum ) it would be impossible to build such a matrix: you would have columns without 1 s or columns with too many 1 s ...

Therefore, your binary matrix is ​​completely determined through rowSum - until its columns are randomly rearranged.

How about this function to build the base matrix b :

 function b = makeBizarreBinaryMatrix( rowSum ) nRows = numel( rowSum ); nCols = sum( rowSum ); rows = 1:nRows; rowInd = zeros( 1, nCols ); rowInd( cumsum( [1 rowSum(1:end-1)] ) ) = 1; rowInd = rows( cumsum( rowInd ) ); b = sparse( rowInd, 1:nCols, 1, nRows, nCols ); 

Now you can use randperm to randomly rearrange the column order:

 nb = b(:, randperm(size(b,2)) ); 

Good luck with your dissertation.

+6
source

All Articles