最近看了一些网上关于用MATLAB实现小世界网络的代码,大部分人在用MATLAB写代码的时候,用的还是C语言里面的思维,一般都是用for之类的循环语句,编写小世界网络时代码往往就大几十行。实际上MATLAB作为矩阵实验室,在利用数组生成对应的网络时,具有无可比拟的优势,下面会把我参考的代码原地址贴上,也会把我修改后的版本附上。
Mathworks
首先,Mathworks官方就给出了《生成 Watts-Strogatz 小世界图形模型》相关的函数代码和对应图的绘制和参数分析。地址:
https://ww2.mathworks.cn/help/matlab/examples/build-watts-strogatz-small-world-graph-model.html
WS小世界网络函数代码如下:
function h = WattsStrogatz(N,K,beta)
% H = WattsStrogatz(N,K,beta) returns a Watts-Strogatz model graph with N
% nodes, N*K edges, mean node degree 2*K, and rewiring probability beta.
%
% beta = 0 is a ring lattice, and beta = 1 is a random graph.
% Connect each node to its K next and previous neighbors. This constructs
% indices for a ring lattice.
s = repelem((1:N)',1,K);
t = s + repmat(1:K,N,1);
t = mod(t-1,N)+1;
% Rewire the target node of each edge with probability beta
for source=1:N
switchEdge = rand(K, 1) < beta;
newTargets = rand(N, 1);
newTargets(source) = 0;
newTargets(s(t==source))