规则网络、随机网络、小世界网络、无标度网络四大经典复杂网络模型的 MATLAB 实现,包含生成、可视化和基本拓扑分析。
MATLAB 实现代码
1 主程序:复杂网络模型演示
matlab
%% 复杂网络基本模型 MATLAB 实现
% 包含:规则网络、随机网络、小世界网络、无标度网络
% 功能:生成、可视化、计算基本拓扑指标
clear; clc; close all;
warning off;
%% 参数设置
N = 100; % 网络节点数
K = 6; % 每个节点的平均连接度(规则网络用)
p_rewire = 0.1; % 小世界网络重连概率
m0 = 3; % 无标度网络初始节点数
m = 2; % 每次新增连接数
fprintf('=== 复杂网络基本模型演示 ===\n');
fprintf('节点数 N = %d\n', N);
fprintf('平均度 K = %d\n', K);
fprintf('小世界重连概率 p = %.2f\n', p_rewire);
fprintf('无标度模型参数 m0=%d, m=%d\n\n', m0, m);
%% 生成四种网络模型
fprintf('正在生成网络模型...\n');
% 1. 规则网络(最近邻耦合网络)
fprintf('1. 生成规则网络...\n');
A_regular = regular_network(N, K);
% 2. 随机网络(Erdos-Renyi模型)
fprintf('2. 生成随机网络...\n');
p_er = K / (N-1); % 连接概率
A_random = erdos_renyi_network(N, p_er);
% 3. 小世界网络(Watts-Strogatz模型)
fprintf('3. 生成小世界网络...\n');
A_smallworld = watts_strogatz_network(N, K, p_rewire);
% 4. 无标度网络(Barabasi-Albert模型)
fprintf('4. 生成无标度网络...\n');
A_scalefree = barabasi_albert_network(N, m0, m);
%% 可视化网络拓扑
fprintf('\n正在可视化网络拓扑...\n');
visualize_networks(A_regular, A_random, A_smallworld, A_scalefree, N);
%% 计算并比较拓扑特性
fprintf('\n=== 网络拓扑特性比较 ===\n');
compare_network_properties(A_regular, A_random, A_smallworld, A_scalefree);
%% 度分布分析
fprintf('\n=== 度分布分析 ===\n');
analyze_degree_distribution(A_regular, A_random, A_smallworld, A_scalefree, N);
%% 聚类系数和平均路径长度
fprintf('\n=== 聚类系数和平均路径长度 ===\n');
calculate_clustering_and_path(A_regular, A_random, A_smallworld, A_scalefree);
%% 鲁棒性分析(可选)
fprintf('\n=== 网络鲁棒性分析 ===\n');
robustness_analysis(A_regular, A_random, A_smallworld, A_scalefree);
fprintf('\n所有分析完成!\n');
2 规则网络生成函数
matlab
function A = regular_network(N, K)
% 生成规则网络(最近邻耦合网络)
% N: 节点数
% K: 每个节点连接的邻居数(偶数)
A = zeros(N, N);
half_K = floor(K/2);
for i = 1:N
for j = 1:half_K
% 连接左右邻居
neighbor1 = mod(i + j - 1, N) + 1;
neighbor2 = mod(i - j - 1 + N, N) + 1;
A(i, neighbor1) = 1;
A(i, neighbor2) = 1;
A(neighbor1, i) = 1;
A(neighbor2, i) = 1;
end
end
% 确保对称且无自环
A = double(A > 0);
A = A - diag(diag(A));
end
3 随机网络生成函数(Erdos-Renyi)
matlab
function A = erdos_renyi_network(N, p)
% 生成Erdos-Renyi随机网络
% N: 节点数
% p: 任意两个节点间存在连接的概率
% 生成随机邻接矩阵
A = rand(N, N) < p;
% 确保对称且无自环
A = triu(A, 1);
A = A + A';
A = double(A > 0);
end
4 小世界网络生成函数(Watts-Strogatz)
matlab
function A = watts_strogatz_network(N, K, p)
% 生成Watts-Strogatz小世界网络
% N: 节点数
% K: 每个节点初始连接的邻居数(偶数)
% p: 重连概率
% 初始化规则网络
A = regular_network(N, K);
% 重连过程
for i = 1:N
neighbors = find(A(i, :));
for j = 1:length(neighbors)
if rand() < p
% 断开原有连接
neighbor = neighbors(j);
A(i, neighbor) = 0;
A(neighbor, i) = 0;
% 随机选择新节点连接(不能与自己连接,不能重复连接)
possible_nodes = setdiff(1:N, [i, find(A(i, :))]);
if ~isempty(possible_nodes)
new_neighbor = possible_nodes(randi(length(possible_nodes)));
A(i, new_neighbor) = 1;
A(new_neighbor, i) = 1;
else
% 如果没有可选节点,恢复原连接
A(i, neighbor) = 1;
A(neighbor, i) = 1;
end
end
end
end
end
5 无标度网络生成函数(Barabasi-Albert)
matlab
function A = barabasi_albert_network(N, m0, m)
% 生成Barabasi-Albert无标度网络
% N: 最终网络节点数
% m0: 初始完全连接的节点数
% m: 每个新节点引入的连接数
% 初始化:创建m0个节点的完全连接网络
A = ones(m0, m0) - eye(m0);
% 逐步添加节点
for new_node = m0+1:N
% 计算现有节点的度
degrees = sum(A, 2);
total_degree = sum(degrees);
% 计算每个节点的连接概率
if total_degree > 0
probs = degrees / total_degree;
else
probs = ones(size(degrees)) / length(degrees);
end
% 根据优先连接选择m个节点连接
selected_nodes = randsample(1:new_node-1, m, true, probs);
% 添加连接
for i = 1:m
target = selected_nodes(i);
A(new_node, target) = 1;
A(target, new_node) = 1;
end
end
end
6 网络可视化函数
matlab
function visualize_networks(A_regular, A_random, A_smallworld, A_scalefree, N)
% 可视化四种网络拓扑
figure('Position', [100, 100, 1200, 900]);
% 布局算法选择
layout_method = 'force3'; % 力导向布局
% 1. 规则网络
subplot(2, 2, 1);
G = graph(A_regular, 'upper');
p = plot(G, 'Layout', layout_method, 'NodeColor', 'b', 'EdgeColor', [0.7 0.7 0.7]);
title(sprintf('规则网络 (N=%d, K=%d)', N, sum(A_regular(1,:))));
set(gca, 'XTick', [], 'YTick', []);
axis equal;
% 2. 随机网络
subplot(2, 2, 2);
G = graph(A_random, 'upper');
p = plot(G, 'Layout', layout_method, 'NodeColor', 'r', 'EdgeColor', [0.7 0.7 0.7]);
title(sprintf('随机网络 (N=%d, p=%.3f)', N, mean(mean(A_random))));
set(gca, 'XTick', [], 'YTick', []);
axis equal;
% 3. 小世界网络
subplot(2, 2, 3);
G = graph(A_smallworld, 'upper');
p = plot(G, 'Layout', layout_method, 'NodeColor', 'g', 'EdgeColor', [0.7 0.7 0.7]);
title(sprintf('小世界网络 (N=%d, p=%.2f)', N, 0.1));
set(gca, 'XTick', [], 'YTick', []);
axis equal;
% 4. 无标度网络
subplot(2, 2, 4);
G = graph(A_scalefree, 'upper');
p = plot(G, 'Layout', layout_method, 'NodeColor', 'm', 'EdgeColor', [0.7 0.7 0.7]);
title(sprintf('无标度网络 (N=%d, m=%d)', N, 2));
set(gca, 'XTick', [], 'YTick', []);
axis equal;
sgtitle('四种基本复杂网络模型拓扑结构', 'FontSize', 16, 'FontWeight', 'bold');
end
7 网络拓扑特性分析函数
matlab
function compare_network_properties(A_regular, A_random, A_smallworld, A_scalefree)
% 比较四种网络的拓扑特性
networks = {A_regular, A_random, A_smallworld, A_scalefree};
names = {'规则网络', '随机网络', '小世界网络', '无标度网络'};
fprintf('%-15s %-10s %-10s %-10s %-10s\n', ...
'网络类型', '节点数', '边数', '平均度', '密度');
fprintf('%-15s %-10s %-10s %-10s %-10s\n', ...
'---------', '-----', '---', '-----', '-----');
for i = 1:length(networks)
A = networks{i};
N = size(A, 1);
edges = sum(A(:)) / 2;
avg_degree = mean(sum(A, 2));
density = edges / (N*(N-1)/2);
fprintf('%-15s %-10d %-10d %-10.2f %-10.4f\n', ...
names{i}, N, edges, avg_degree, density);
end
end
8 度分布分析函数
matlab
function analyze_degree_distribution(A_regular, A_random, A_smallworld, A_scalefree, N)
% 分析四种网络的度分布
figure('Position', [100, 100, 1200, 400]);
networks = {A_regular, A_random, A_smallworld, A_scalefree};
names = {'规则网络', '随机网络', '小世界网络', '无标度网络'};
colors = {'b', 'r', 'g', 'm'};
for i = 1:length(networks)
subplot(2, 2, i);
A = networks{i};
% 计算每个节点的度
degrees = sum(A, 2);
% 绘制度分布直方图
max_deg = max(degrees);
bins = 0:max_deg;
histogram(degrees, bins, 'Normalization', 'probability', ...
'FaceColor', colors{i}, 'EdgeColor', 'k', 'LineWidth', 1);
xlabel('节点度 k');
ylabel('概率 P(k)');
title(names{i});
grid on;
% 对于无标度网络,绘制幂律拟合
if i == 4
hold on;
% 简单的幂律拟合
k_min = 1;
k_max = max_deg;
k_range = k_min:k_max;
% 计算经验分布
hist_counts = histcounts(degrees, k_range, 'Normalization', 'probability');
% 寻找非零区间
nonzero_idx = hist_counts > 0;
if any(nonzero_idx)
k_fit = k_range(nonzero_idx);
p_fit = hist_counts(nonzero_idx);
% 对数坐标下的线性拟合
log_k = log(k_fit);
log_p = log(p_fit);
% 移除无穷大值
valid_idx = isfinite(log_k) & isfinite(log_p);
if sum(valid_idx) > 2
coeffs = polyfit(log_k(valid_idx), log_p(valid_idx), 1);
gamma = -coeffs(1);
% 绘制拟合曲线
k_plot = linspace(min(k_fit), max(k_fit), 100);
p_plot = exp(coeffs(2)) * k_plot.^(-gamma);
plot(k_plot, p_plot, 'k--', 'LineWidth', 2, 'DisplayName', ...
sprintf('幂律拟合 γ=%.2f', gamma));
legend('Location', 'best');
end
end
hold off;
end
end
sgtitle('四种网络的度分布比较', 'FontSize', 14, 'FontWeight', 'bold');
end
9 聚类系数和平均路径长度计算
matlab
function calculate_clustering_and_path(A_regular, A_random, A_smallworld, A_scalefree)
% 计算聚类系数和平均路径长度
networks = {A_regular, A_random, A_smallworld, A_scalefree};
names = {'规则网络', '随机网络', '小世界网络', '无标度网络'};
fprintf('%-15s %-15s %-15s\n', '网络类型', '聚类系数 C', '平均路径长度 L');
fprintf('%-15s %-15s %-15s\n', '---------', '-----------', '---------------');
for i = 1:length(networks)
A = networks{i};
N = size(A, 1);
% 计算聚类系数
clustering_coeff = calculate_clustering_coefficient(A);
% 计算平均路径长度(使用Floyd-Warshall算法)
avg_path_length = calculate_average_path_length(A);
fprintf('%-15s %-15.4f %-15.4f\n', names{i}, clustering_coeff, avg_path_length);
end
end
function C = calculate_clustering_coefficient(A)
% 计算网络的聚类系数
N = size(A, 1);
C = 0;
for i = 1:N
neighbors = find(A(i, :));
k = length(neighbors);
if k < 2
continue;
end
% 计算邻居之间的连接数
subgraph = A(neighbors, neighbors);
connections = sum(subgraph(:)) / 2; % 除以2避免重复计数
% 三角形最大可能数
max_triangles = k * (k - 1) / 2;
% 节点i的聚类系数
Ci = connections / max_triangles;
C = C + Ci;
end
C = C / N; % 平均聚类系数
end
function L = calculate_average_path_length(A)
% 计算网络的平均路径长度(使用Floyd-Warshall算法)
N = size(A, 1);
% 初始化距离矩阵
D = inf(N, N);
% 设置直接连接的节点距离为1
for i = 1:N
for j = 1:N
if A(i, j) == 1
D(i, j) = 1;
end
end
D(i, i) = 0; % 自己到自己的距离为0
end
% Floyd-Warshall算法
for k = 1:N
for i = 1:N
for j = 1:N
if D(i, k) + D(k, j) < D(i, j)
D(i, j) = D(i, k) + D(k, j);
end
end
end
end
% 计算平均路径长度(排除不可达节点)
reachable = D < inf;
total_paths = sum(reachable(:)) - N; % 减去对角线元素
if total_paths > 0
L = sum(D(reachable)) / total_paths;
else
L = inf;
end
end
10 网络鲁棒性分析
matlab
function robustness_analysis(A_regular, A_random, A_smallworld, A_scalefree)
% 分析网络对随机攻击和针对性攻击的鲁棒性
networks = {A_regular, A_random, A_smallworld, A_scalefree};
names = {'规则网络', '随机网络', '小世界网络', '无标度网络'};
colors = {'b', 'r', 'g', 'm'};
figure('Position', [100, 100, 1200, 500]);
for i = 1:length(networks)
subplot(2, 2, i);
A = networks{i};
N = size(A, 1);
% 初始化
f_values = 0:0.05:0.5; % 移除节点比例
random_attack = zeros(size(f_values));
targeted_attack = zeros(size(f_values));
% 多次模拟取平均
num_simulations = 10;
for sim = 1:num_simulations
% 随机攻击
for idx = 1:length(f_values)
f = f_values(idx);
nodes_to_remove = randperm(N, round(f*N));
A_temp = remove_nodes(A, nodes_to_remove);
random_attack(idx) = random_attack(idx) + largest_component_size(A_temp)/N;
end
% 针对性攻击(移除度最高的节点)
for idx = 1:length(f_values)
f = f_values(idx);
degrees = sum(A, 2);
[~, sorted_idx] = sort(degrees, 'descend');
nodes_to_remove = sorted_idx(1:round(f*N));
A_temp = remove_nodes(A, nodes_to_remove);
targeted_attack(idx) = targeted_attack(idx) + largest_component_size(A_temp)/N;
end
end
% 取平均
random_attack = random_attack / num_simulations;
targeted_attack = targeted_attack / num_simulations;
% 绘制曲线
plot(f_values, random_attack, 'Color', colors{i}, 'LineWidth', 2, 'LineStyle', '-', ...
'DisplayName', '随机攻击');
hold on;
plot(f_values, targeted_attack, 'Color', colors{i}, 'LineWidth', 2, 'LineStyle', '--', ...
'DisplayName', '针对性攻击');
xlabel('移除节点比例 f');
ylabel('最大连通分量相对大小 S/S_0');
title(names{i});
legend('Location', 'best');
grid on;
hold off;
end
sgtitle('网络鲁棒性分析:随机攻击 vs 针对性攻击', 'FontSize', 14, 'FontWeight', 'bold');
end
function A_new = remove_nodes(A, nodes_to_remove)
% 从网络中移除指定节点
A_new = A;
A_new(nodes_to_remove, :) = 0;
A_new(:, nodes_to_remove) = 0;
end
function size_lcc = largest_component_size(A)
% 计算最大连通分量的大小
% 使用广度优先搜索
N = size(A, 1);
visited = false(N, 1);
max_size = 0;
for i = 1:N
if ~visited(i)
% 开始新的BFS
queue = i;
visited(i) = true;
component_size = 0;
while ~isempty(queue)
current = queue(1);
queue(1) = [];
component_size = component_size + 1;
% 找到所有邻居
neighbors = find(A(current, :));
for j = 1:length(neighbors)
if ~visited(neighbors(j))
visited(neighbors(j)) = true;
queue(end+1) = neighbors(j);
end
end
end
if component_size > max_size
max_size = component_size;
end
end
end
size_lcc = max_size;
end
参考代码 复杂网络中基本网络模型的matlab实现 www.youwenfan.com/contentcst/77685.html
使用说明
1. 运行方式
- 将所有函数保存为
.m文件 - 运行主程序
main_complex_networks.m - 查看生成的图表和分析结果
2. 参数调整
matlab
% 在主程序中调整这些参数
N = 100; % 网络规模
K = 6; % 平均度
p_rewire = 0.1; % 小世界重连概率
m0 = 3; % 无标度初始节点
m = 2; % 新增连接数
3. 预期输出
- 网络拓扑图:四种网络的直观可视化
- 拓扑特性表:节点数、边数、平均度、密度
- 度分布图:特别是无标度网络的幂律分布
- 聚类系数和路径长度:小世界特性的量化
- 鲁棒性分析:随机攻击 vs 针对性攻击
理论特性对比
| 网络类型 | 聚类系数 | 平均路径长度 | 度分布 | 鲁棒性 |
|---|---|---|---|---|
| 规则网络 | 高 | 大 | 窄峰分布 | 对攻击敏感 |
| 随机网络 | 低 | 小 | 泊松分布 | 对攻击不敏感 |
| 小世界网络 | 高 | 小 | 接近泊松 | 介于两者之间 |
| 无标度网络 | 变化大 | 小 | 幂律分布 | 对随机攻击鲁棒,对针对性攻击脆弱 |
扩展应用
1. 传染病传播模型
matlab
% 在复杂网络上模拟SIR模型
function simulate_epidemic(A, beta, gamma)
% beta: 感染率
% gamma: 恢复率
% A: 网络邻接矩阵
N = size(A, 1);
states = zeros(N, 1); % 0=S, 1=I, 2=R
initial_infected = randperm(N, 5); % 初始5个感染者
states(initial_infected) = 1;
% 时间演化
for t = 1:100
new_states = states;
for i = 1:N
if states(i) == 1 % 感染者
% 尝试感染邻居
neighbors = find(A(i, :));
for j = 1:length(neighbors)
if states(neighbors(j)) == 0 && rand() < beta
new_states(neighbors(j)) = 1;
end
end
% 恢复
if rand() < gamma
new_states(i) = 2;
end
end
end
states = new_states;
end
end
2. 同步现象分析
matlab
% Kuramoto模型在复杂网络上的同步
function kuramoto_model(A, coupling_strength)
% 在复杂网络上模拟相位振荡器的同步
N = size(A, 1);
phases = 2*pi*rand(N, 1); % 初始相位
natural_freq = 0.1*randn(N, 1); % 自然频率
dt = 0.01;
for t = 1:1000
dphases = zeros(N, 1);
for i = 1:N
neighbors = find(A(i, :));
coupling_term = 0;
for j = 1:length(neighbors)
coupling_term = coupling_term + sin(phases(neighbors(j)) - phases(i));
end
dphases(i) = natural_freq(i) + coupling_strength/N * coupling_term;
end
phases = phases + dphases * dt;
end
end
3. 社区发现算法
matlab
% 基于模块度的社区发现
function communities = detect_communities(A)
% 使用Louvain算法检测社区结构
N = size(A, 1);
communities = ones(N, 1); % 初始每个节点为一个社区
% 计算模块度
m = sum(A(:))/2; % 总边数
degrees = sum(A, 2);
improved = true;
while improved
improved = false;
for i = 1:N
current_comm = communities(i);
best_comm = current_comm;
best_delta = 0;
% 尝试移动到邻居所在的社区
neighbors = find(A(i, :));
unique_comms = unique(communities(neighbors));
for comm = unique_comms'
if comm ~= current_comm
delta_q = calculate_modularity_change(A, communities, i, comm, m, degrees);
if delta_q > best_delta
best_delta = delta_q;
best_comm = comm;
end
end
end
if best_comm ~= current_comm
communities(i) = best_comm;
improved = true;
end
end
end
end
参考文献
- Watts, D. J., & Strogatz, S. H. (1998). Collective dynamics of 'small-world' networks. Nature, 393(6684), 440-442.
- Barabási, A. L., & Albert, R. (1999). Emergence of scaling in random networks. Science, 286(5439), 509-512.
- Newman, M. E. J. (2003). The structure and function of complex networks. SIAM Review, 45(2), 167-256.
- Albert, R., & Barabási, A. L. (2002). Statistical mechanics of complex networks. Reviews of Modern Physics, 74(1), 47-97.