如何在Matlab中使用0s和1s的对称矩阵找到分离的链接块的数量?
例如,在矩阵A中,如果A(n,m)= 1,则成员n和m连接。连接元素制作块。在下面的矩阵中,成员2,3,4,5,6,8,9连接并形成一个块。此外,有两个大小等于2的簇和一个大小为7的块。
A = [1 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 0 1 1 0
0 1 1 1 1 1 0 1 1 0
0 1 1 1 1 1 0 1 1 0
0 1 1 1 1 1 0 1 1 0
0 1 1 1 1 1 0 1 1 0
0 0 0 0 0 0 1 0 0 0
0 1 1 1 1 1 0 1 1 0
0 1 1 1 1 1 0 1 1 0
0 0 0 0 0 0 0 0 0 1]
答案 0 :(得分:0)
按照上一个问题(link),您可以使用标签而不是二元指示,然后使用每个街区中的成员数量:
A = false(10);
% direct connections
A(2,3) = 1;
A(3,4) = 1;
A(5,6) = 1;
A(4,9) = 1;
A = A | A';
B = double(A | diag(ones(1,10))); % each node is connected to it self
B(B == 1) = 1:nnz(B); % set initial unique labels
while true
B_old = B;
% connect indirect connected nodes
for node = 1:size(B,1)
row = B(node,:);
col = row';
row = row > 0;
col(col > 0) = max(col);
cols = repmat(col,[1 nnz(row)]);
% set the same label for each group of connected nodes
B(:,row) = max(B(:,row) , cols);
end
if isequal(B,B_old)
break
end
end
% get block size
u = unique(B);
counts = hist(B(:),u);
% remove non connections
counts(u == 0) = [];
u(u == 0) = [];
% remove self connections
u(counts == 1) = [];
counts(counts == 1) = [];
% block size
blocksize = sqrt(counts);