将邻接矩阵转换为图形 - matgraph

时间:2015-11-20 20:09:35

标签: matlab matrix graph adjacency-list adjacency-matrix

首先我应该注意这是关于 Stack Overflow 的第一个问题,所以请原谅我的问题的演示文稿和格式中的任何错误!

我有以下代码将mx3 .txt 文件转换为邻接矩阵:

% Converts edge list to adjacency matrix
% INPUTS: edgelist: mx3
% OUTPUTS: adjacency matrix nxn
% Note: information about nodes is lost: indices only (i1,...in) remain
% Gergana Bounova, Last updated: October 6, 2009

function adj=edgeL2adj(el)   

nodes=sort(unique([el(:,1) el(:,2)]));             % get all nodes, sorted
n=numel(nodes);                                    % number of unique nodes
adj=zeros(n);                                      % initialize adjacency matrix

for i=1:size(el,1)                                 % across all edges
  adj(find(nodes==el(i,1)),find(nodes==el(i,2)))=el(i,3);
end

如果我有一个mx3边缘列表作为我的输入,我们称之为网络我创建一个矩阵, A 。然后,我使用 matgraph 为此邻接矩阵创建关联图。但我仍然遇到如下所示的错误:

A=edgeL2adj(Network);
graph_init;
G=graph;
set_matrix(G,A);

其中“set_matrix.m”是以下函数:

function set_matrix(g,A)
      % set_matrix(g,A) --- set g to be the graph specificed in the matrix A.
      % The matrix is scanned by check_matrix to be sure it is a valid adjacency
      % matrix. If it is not, an error is triggered and the graph is left
      % unchanged. 
if (~check_matrix(A))
   error('Input matrix is not a valid adjacency matrix')
end

fast_set_matrix(g,logical(A));

但后来我收到了错误,

Error using graph/set_matrix (line 8)
Input matrix is not a valid adjacency matrix

然后我检查了脚本中的“check_matrix.m”,其内容如下:

function ok = check_matrix(A)
% check_matrix(A) --- check if A is a valid adjacency matrix for a graph
ok = 0;
% make sure matrix is square
[nr,nc] = size(A);
if (nr ~= nc) 
    return
end
% see if the matrix is zero-one
B = (A>0); % convert to logical (so 0,1).
if (nnz(A-B)>0)
    return
end
% check if symmetric
if (nnz(A-A')>0)
    return
end
% check the diagonal
if (any(diag(A)>0)) 
    return
end
% all tests passed
ok = 1;

依次遍历每个点,我发现 A 没有完全由零组成的对角线,而是由1和0组成。现在,在主对角线和邻接矩阵中具有任何1值是没有意义的,因为从节点到自身不存在任何长度为1的步长;从节点到自身的无向网络中最短的封闭行走是2。

有没有人想知道为什么函数“adj = edgeL2adj(el).m”在将 .txt 文件转换为有效的邻接矩阵时没有用?我曾想过尝试将主对角线“归零”,但不知道这是否会改变矩阵,因此渲染所有后续分析并且工作错误。

干杯!

编辑:以下是.txt文件的前十行:

1   1   1
4   1   1
2530    1   1
4   2   1
6   2   1
571 2   1
2275    3   1
1   4   1
2   4   1
6   4   1

0 个答案:

没有答案