用Matlab打印最大度数的n个节点

时间:2014-10-16 00:07:41

标签: matlab graph

我需要一个matlab脚本,它将在图形中返回最大程度的n个节点 例如:

N = maxnodes(Graph,n)
  • 图表是一个矩阵
  • n 我们需要的节点数
  • N 是一个包含n个节点的向量。

这是我的源代码(脚本)。但它效果不佳。
    

M = [0 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0;
1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0;
0 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0;
0 0 1 0 1 0 0 1 0 0 0 0 0 0 0 0;
0 0 1 1 0 1 0 0 0 0 0 1 0 0 0 0;
1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0;
1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0;
0 0 0 1 0 0 0 0 1 1 0 0 0 0 0 0;
0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1;
0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0;
0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0;
0 0 0 0 0 0 0 0 0 1 1 0 1 0 0 0;
0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0;
0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0;
0 0 0 0 0 0 0 0 0 1 0 0 1 1 0 1;
0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0;];

n = 5; % The number of nodes that we want

G=[]; % I'll store here the n nodes of maximum degree

for i=1:size(M)
G1(1,i)=sum(M(i,:)); % I'm storing each node with its degree in G1
G1(2,i)=i;

C(1,i)=G1(1,i); %I store only degree of nodes
end
C1 = sort(C,'descend'); % I sort "descendly" the degrees of nodes

for i=1:n %We want to take only the n nodes that we need and save it in C2
C2(1,i) = C1(1,i);
end 
C2; % This vector stores the n descend maximum degrees that I need. 

%My actual problem is here. How could I find the node that correspond to each degree?    
%I tried to do it with the following loop:
for j=1:n
for i=1:size(M)
if C2(1,j) == G1(1,i)
G2(1,j)=G1(2,i);
end
end
end %But this loop doesn't store well the nodes in G2 because it repeats nodes. 
G2 

2 个答案:

答案 0 :(得分:0)

你绝对没有表现出任何努力,所以你实际上不应该得到任何人的任何帮助....但我喜欢图形问题,所以我会给你一块骨头。


我将假设Graphadjacency matrix,其中矩阵中的每个元素(i,j)都对应于两个节点之间连接的边ij。我也假设你有一个无向图作为输入。如果你检查邻接矩阵的性质(维基百科文章有一个很好的例子),不难看出节点i的程度只是行的所有列的总和。邻接矩阵中的i。回想一下,度被定义为连接到特定节点的边的总数。因此,您所要做的就是对每行的所有列求和,并确定图中具有最大度数的行。完成此操作后,我们只返回具有最大度数的节点,该节点最多为n

但是,如果我们指定n大于具有此最大程度的节点数,我们将设置一个安全措施,我们将限制它,以便我们只显示这么多节点而不是{{ 1}}。

因此:

n

答案 1 :(得分:0)

这是一个非常有效的脚本,可以解决我的问题。否则,我会很高兴上面的源代码将是调试。

function N = maxnodes(M,n)
nb1_rows= sum(M,2); 
[nbs,is] = sort(nb1_rows,'descend');
N = transpose(is(1:n));
相关问题