i want to get adjacency matrix of a network
7 次查看(过去 30 天)
显示 更早的评论
i have write this but is not running
clc;
clear all
n=10;
p=0.4;
adj_matrix = generate_adjacency_matrix(n, p);
function adj_matrix = generate_adjacency_matrix(n, p)
% Initialize an n x n matrix with all zeros
adj_matrix = zeros(n, n);
% Loop through all possible node pairs
for i = 1:n
for j = 1:n
% Skip diagonal elements (no self-loops)
if i == j
continue;
end
% Generate a random number between 0 and 1
random_number = rand();
% If the random number is less than p, add a link between nodes i and j
if random_number < p
adj_matrix(i, j) = 1;
adj_matrix(j, i) = 1; % Since it's an undirected network
end
end
end
end
disp(adj_matrix);
1 个评论
Bruno Luong
2023-7-30
编辑:Bruno Luong
2023-7-30
@MD KAUSAR SK The answer thread is unlike undirected graph, you should not duplicate it https://www.mathworks.com/matlabcentral/answers/2002382-network-adjacency-matrix-for-connecting-n-node-with-probability-p?s_tid=srchtitle
回答(2 个)
Steven Lord
2023-7-30
If you want to generate both the graph object and its adjacency matrix, tell MATLAB to build the graph using just the upper triangular part of the random matrix.
n = 10;
p = 0.6;
A = rand(n) < p;
G = graph(A, 'upper');
adj = full(adjacency(G))
check = triu(A)+triu(A, 1).'
isequal(adj, check)
2 个评论
Steven Lord
2023-7-30
Since I created the graph object before creating the adjacency matrix, just plot it.
plot(G)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graph and Network Algorithms 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!