我需要创建零对角线的所有0,1 NxN矩阵。矩阵必须是对称的。在每一列和每行必须至少有一个1.任何可以帮助的想法?
答案 0 :(得分:2)
获取该表单的所有可能的矩阵
这个想法是这种类型的大小为NxN的矩阵由其上对角线值定义。因此,迭代上对角线部分的所有可能模式,并将这些值应对到下对角线将起到作用。 代码示例:
%defines N
N = 3;
%calculates degree of freedom
nValuesToRand = ((N*N) - N)/2;
%generate all possible binary patterns of size nValuesToRand
B = dec2bin(0:2^nValuesToRand - 1);
%masks of lower and upper diagonal - will be used later on
upperTriagonalMask = logical(triu(ones(N,N)) - eye(N));
lowerTriagonalMask = logical(tril(ones(N,N)) - eye(N));
%generates a new cell to hold the matrices
allMatrices = cell(size(B,1),1);
%iterates over all possible patterns
for i=1:size(B,1)
%generates a new matrix
mat = zeros(N,N);
%initializes its upper diagonal according to the binary pattern
mat(upperTriagonalMask) = logical(B(i,:)- 48);
%copies the upper triagonal to the lower triagonal (for symmetricality)
upperTriagonalTransposed = triu(mat)';
mat(lowerTriagonalMask) = upperTriagonalTransposed(lowerTriagonalMask);
%ignores illegal Matrices
if sum(sum(mat,2)==0)>0
continue;
end
%saves mat in the cell
allMatrices{i} = mat;
end
%cleanes cell
allMatrices = allMatrices(~cellfun(@isempty, allMatrices));
随机矩阵生成
为大N值生成所有可能的矩阵在计算上是困难的。 如果要随机生成矩阵,可以尝试以下方法:
%Dimension size
N = 6;
%Probability for appearance of 0
P = 0.5;
%A mask of the lower diagonal, to be used later on
lowerTriagonalMask = logical(tril(ones(N,N)));
%initializes the matrix
mat = zeros(N,N);
%runs the loop as long as the matrix is not valid
while (sum(mat,2)==0)>0
%defines a random binary matrix
mat = rand(N,N) > P;
%zero out the diagonal values
mat(logical(eye(N))) = 0;
%copies the upper triagonal to the lower triagonal (for symmetricality)
upperTriagonalTransposed = triu(mat)';
mat(lowerTriagonalMask) = upperTriagonalTransposed(lowerTriagonalMask);
end
%testing
issymmetric(double(mat))
mat
结果:
ans =
1
mat =
0 1 1 1 0 0
1 0 1 1 1 1
1 1 0 0 0 1
1 1 0 0 0 1
0 1 0 0 0 1
0 1 1 1 1 0