计算图的平均聚类系数 我得到了正确的结果,但是图形尺寸增加需要一些替代方法需要花费大量时间,因此执行时间较短.有没有办法简化代码? %// A is adjacency matrix N X N, %// d is degree , N
我得到了正确的结果,但是图形尺寸增加需要一些替代方法需要花费大量时间,因此执行时间较短.有没有办法简化代码?
%// A is adjacency matrix N X N, %// d is degree , N=100; d=10; rand('state',0) A = zeros(N,N); kv=d*(d-1)/2; %% Creating A matrix %%% for i = 1:(d*N/2) j = floor(N*rand)+1; k = floor(N*rand)+1; while (j==k)||(A(j,k)==1) j = floor(N*rand)+1; k = floor(N*rand)+1; end A(j,k)=1; A(k,j)=1; end %% Calculation of clustering Coeff %% for i=1:N J=find(A(i,:)); et=0; for ii=1:(size(J,2))-1 for jj=ii+1:size(J,2) et=et+A(J(ii),J(jj)); end end Cv(i)=et/kv; end Avg_clustering_coeff=sum(Cv)/n;
输出我得到了.
Avg_clustering_coeff = 0.1107
可以使用nchoosek
对聚类Coeff部分的计算进行矢量化以移除最里面的两个嵌套循环,如下所示 –
CvOut = zeros(1,N); for k=1:N J=find(A(k,:)); if numel(J)>1 idx = nchoosek(J,2); CvOut(k) = sum(A(sub2ind([N N],idx(:,1),idx(:,2)))); end end CvOut=CvOut/kv;
希望这会提升性能相当多!