本帖最后由 枫叶舞流星 于 2020-12-19 21:18 编辑
运行WS_net.m文件
得到小世界网络图的平均路径长度为0,不知道哪里错了,求大神指点
好像是dijkstra.m文件的错误,dist值都为0.
以下是代码
WS_net.m文件
N=20; %节点
K=7; %度
p=0.35;
if K>floor(N/2)
disp('输入的K值不合法')
return;
end
angle=0:2*pi/N:2*pi-2*pi/N;
x=100*sin(angle);
y=100*cos(angle);
plot(x,y,'ro','MarkerEdgeColor','g','MarkerFaceColor','r','markersize',8);hold on;
A=zeros(N);
for u=1:N
for v=u+1:u+K
vv=v;
if v>N
vv=mod(v,N);
end
A(u,vv)=1; A(vv,u)=1;
end
end
for u=1:N
for v=u+1:u+K
vv=v;
if v>N
vv=mod(v,N);
end
p1=rand(1,1);
if p1
A(u,vv)=0;A(vv,u)=0;
A(u,u)=inf; a=find(A(u,:)==0);
rand_data=randi([1,length(a)],1,1); %新版本的randint()不能用,使用randi代替
vvv=a(rand_data);
A(u,vvv)=1;A(vvv,u)=1;
A(u,u)=0;
end
end
end
for u=1:N
for v=u+1:N
if A(u,v)~=0
plot([x(u),x(v)],[y(u),y(v)],'linewidth',1.2); hold on;
end
end
end
axis equal;
hold off
[C,cp]=Clustering_Coefficient(A,N);
disp(['该小世界网络图的聚类系数为',num2str(cp)]);
lp=SpecLength(A,N);
disp(['该小世界网络图的平均路径长度为',num2str(lp)]);
function [output_args] = SpecLength(A,N)
%UNTITLED5 Summary of this function goes here
% Detailed explanation goes here
output_args= 0;
for s=1:1:N
[dist,route]=dijkstra(A,s);
d=sum(dist);
output_args =output_args +d;
end
output_args = output_args/(0.5*N*(N-1));
end
function [dist,route]=dijkstra(A,s)
n=length(A);
route=1:n;
B=1:n;B(B==s)=[];
dist=A(s,:);
while ~isempty(B)
cur_dist=dist(B);
[~,ind]=min(cur_dist);
via=B(ind);
dist_via=dist(via)+A(via,B);
update_ind=cur_dist>dist_via;
cur_dist(update_ind)=dist_via(update_ind);
dist(B)=cur_dist;
route(B(update_ind))=via;
B(ind)=[];
end
function [C,cp]=Clustering_Coefficient(A,N)
neighbor =[];neighbor_index =[];
for k=1:N
neighbor(k)=0;
end
edge =[];
for k=1:N
edge(k)=0;
end
for u=1:N
count=1;
for v=1:N
if(A(u,v)~=0)
neighbor(u) = neighbor(u)+ 1;
neighbor_index(u,count)=v;
count = count +1;
end
end
neighbor_index(u,count)=u;
end
for p=1:1:length(neighbor_index)
for m=1:1:length(neighbor_index(1,:))
edge(p,m)=0;
for n=m+1:1:length(neighbor_index(1,:))
if(neighbor_index(p,m)~=0 && neighbor_index(p,n)~=0)
if(A(neighbor_index(p,m),neighbor_index(p,n))==1)
edge(p,m)=edge(p,m)+1;
end
end
end
end
edge_sum(p)=sum(edge(p,:));
end
for u=1:1:N
C(u)=2*edge_sum(u)/(neighbor(u)*(neighbor(u)-1));
end
cp= mean(C);
end
2020-12-19 21:03 上传
点击文件名下载附件
373 Bytes, 下载次数: 0
2020-12-19 21:04 上传
点击文件名下载附件
1.18 KB, 下载次数: 0
2020-12-19 21:04 上传
点击文件名下载附件
330 Bytes, 下载次数: 0
2020-12-19 21:04 上传
点击文件名下载附件
914 Bytes, 下载次数: 0