WS小世界網絡生成算法,一般小世界網絡生成算法速度慢,節點度分布與數學推導不符,在網絡仿真中造成不便,這里針對實際網絡動力學仿真過程撰寫了WS小世界網絡的MATLAB生成算法,並考慮了矩陣化,具有較高的速度。
以下是対應的代碼:
% The simulation of WS-smallworld network % the algorithm of WS-smallworld's generation has been improved in speed, % and tend to be easily understood % writen by winter-my-dream@hotmail.com % Example: % N = 100; %network size (number of nodes) % m = 6; %2*m is the average edges of each nodes % p = 0.1; %rewiring probability % matrix = small_world_WS_new(N,m,p); function matrix = small_world_WS_new(N,m,p) rng('default') rng('shuffle') matrix=zeros(N,N); % generate regular network for i=m+1:N-m matrix(i,i-m:i+m)=1; end for i=1:m matrix(i,1:i+m)=1; end for i=N-m+1:N matrix(i,i-m:N)=1; end for i=1:m matrix(i,N-m+i:N)=1; matrix(N-m+i:N,i)=1; end % rewiring the network for i = 1:N % then rewiring the edges with the probability of p [series1,series2] = range_sort(N,m,i); index0 = series1(rand(2*m,1)>1-p); if(~isempty(index0)) matrix(i,index0) = 0; matrix(i,series2(randperm(length(series2),length(index0))))=1; end end matrix = matrix -diag(diag(matrix)); end function [series1,series2] = range_sort(N,m,i) % select the index of nodes in row i for rewiring if(i-m>0 && i+m<=N) series1 = i-m:i+m; series2 = setdiff(1:N,series1); elseif(i-m<=0) series1 = [1:i+m,N-m+i:N]; series2 = setdiff(1:N,series1); else series1 = [1:m-N+i,i-m:N]; series2 = setdiff(1:N,series1); end % Without considering the connection of diagonal elements series1(series1==i) = []; end
參考文獻:
Watts D J, Strogatz S H. Collective dynamics of ‘small-world’networks[J]. nature, 1998, 393(6684): 440-442.
NW小世界網絡的生成方法相對簡單,我這里附加對應代碼:
% 基於Matlab 的小世界網絡仿真 % 經過矩陣化修改后,生成速度已經大大加快 function matrix = small_world_NW(N,m,p) % N=50;m=3;p=0.1; % matrix=sparse([]); matrix = zeros(N,N); for i=m+1:N- m matrix(i,i- m:i+m)=1; end for i=1:m matrix(i,1:i+m)=1; end for i=N- m+1:N matrix(i,i- m:N)=1; end for i=1:m matrix(i,N- m+i:N)=1; matrix(N- m+i:N,i)=1; end % Random add edge kk=(rand(N,N)<p); matrix = logical(matrix + kk); matrix = matrix -diag(diag(matrix));
對應生成網絡的測試圖的代碼:
clear,clc,close all % load A.txt N=10; m=2; p=0.1; % A= small_world_WS_new(N,m,p); A = small_world_NW(N, m, p); t=linspace(0,2*pi,N+1); x=sin(t); y=cos(t); figure set(gcf,'color','w') plot(x,y,'o','markerfacecolor','k'),hold on for i=1:N for j=1:N if (A(i,j)==1) fp1=plot([x(i),x(j)],[y(i),y(j)],'r-'); hold on set(fp1,'linesmoothing','on') end end end axis([-1.05,1.05,-1.05,1.05]) axis square axis off sum(sum(A))