[英]construct a binary matrix such that each column contains only single “1” and sum of each row is of desired value
I want to construct a binary(0s and 1s) matrix satisfying the following constraints: 我想构造一个满足以下约束的二进制(0s和1s)矩阵:
Each column must contains only single binary 1 and rest elements of that column are 0s. 每列必须仅包含单个二进制1,并且该列的其余元素为0。
The sum of each ROW of matrix should be a desired value. 矩阵的每个ROW的总和应为所需值。 For example, given a
rowSum
vector of [5 7 6 8 .......] then the sum of first row should be 5, sum of second row should be 7 and so on. 例如,给定
rowSum
向量为[5 7 6 8 .......],则第一行的总和应为5,第二行的总和应为7,依此类推。
nCol
== Sum(rowSum)
nCol
== Sum(rowSum)
Moreover, I would like to consider several (eg, 7) matrices satisfying the same conditions. 此外,我想考虑几个 (例如7个)满足相同条件的矩阵。
EDIT: 编辑:
I have tried to write the code and completed the one part of it. 我试图编写代码并完成其中一部分。 The code is:
代码是:
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
It would not always be possible to construct a binary matrix that satisfies your requirements. 构造满足您要求的二进制矩阵并不总是可能的。 Suppose you want a binary matrix of size
nRows
x nCols
with rowSum
(a vector of length nRows
) rowSum(k)
the number of 1
s in k
th row. 假设您想要一个大小为
nRows
x nCols
的二进制矩阵,其中rowSum
(长度为nRows
的向量) rowSum(k)
在第k
行中的个数为1
s。 So, if nCol ~= sum( rowSum )
it would be impossible to construct such matrix: you would either have columns with no 1
s, or columns with too many 1
s... 因此,如果
nCol ~= sum( rowSum )
则不可能构造这样的矩阵:您将拥有无1
s的列,或具有过多1
s的列...
Therefore, your binary matrix is completely defined through rowSum
- up to random permutation of its columns. 因此,您的二进制矩阵是通过
rowSum
完全定义的-直至其列的随机排列。
How about this function to construct the basic matrix b
: 这个函数如何构造基本矩阵
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 permute the order of the columns: 现在,您可以使用
randperm
随机排列列的顺序:
nb = b(:, randperm(size(b,2)) );
Good luck with your thesis. 祝你好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.