matlab small world model

官方提供的函数:

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矩阵的意义在于:一共有k列,每行的索引代表了每个node。
%如第一行是[2,3]代表第一个node与node#2,node#3相连
t = s + repmat(1:K,N,1);
%之所以要取模加一,是因为:
%例如N=10,那么node#10肯定要与node#1,node#2相连
t = mod(t-1,N)+1;

% Rewire the target node of each edge with probability beta
for source=1:N   
    %生成k*1的随机logic矩阵,随机值<beta即表示边被选中需要重连 
    switchEdge = rand(K, 1) < beta;
    newTargets = rand(N, 1);
    newTargets(source) = 0;%避免自连
    %即表示只能重连node#source指向的node,而其他指向node#source的边
    %不能被重连
    newTargets(s(t==source)) = 0;
    %未被选中的边也不能被重连
    newTargets(t(source, ~switchEdge)) = 0;
    %按之前生成的随机概率,降序排列, 返回索引
    [~, ind] = sort(newTargets, 'descend');
    %nnz返回switchEdge中非零元素个数(即需要重连的边的数目)
    %再重连边
    t(source, switchEdge) = ind(1:nnz(switchEdge));
end

h = graph(s,t);
end

猜你喜欢

转载自blog.csdn.net/normol/article/details/79155147