i want to get adjacency matrix of a network

조회 수: 5 (최근 30일)
mks
mks 2023년 7월 30일
댓글: Steven Lord 2023년 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);

답변 (2개)

Matt J
Matt J 2023년 7월 30일
편집: Matt J 2023년 7월 30일
Easier:
function adj_matrix = generate_adjacency_matrix(n, p)
adj_matrix=triu(rand(n)<p,1);
adj_matrix=adj_matrix+adj_matrix'; % Since it's an undirected network
end

Steven Lord
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))
adj = 10×10
0 0 1 0 0 1 0 1 0 0 0 1 0 1 1 1 0 1 1 1 1 0 1 1 0 1 0 1 0 1 0 1 1 1 1 1 0 1 1 1 0 1 0 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 1 0 0 0 1 0 1 1 1 0 0 1 1 0 1 1 1 1 0 1 0 1 1
check = triu(A)+triu(A, 1).'
check = 10×10
0 0 1 0 0 1 0 1 0 0 0 1 0 1 1 1 0 1 1 1 1 0 1 1 0 1 0 1 0 1 0 1 1 1 1 1 0 1 1 1 0 1 0 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 1 0 0 0 1 0 1 1 1 0 0 1 1 0 1 1 1 1 0 1 0 1 1
isequal(adj, check)
ans = logical
1
  댓글 수: 2
mks
mks 2023년 7월 30일
이동: Bruno Luong 2023년 7월 30일
how can draw it ?
Steven Lord
Steven Lord 2023년 7월 30일
Since I created the graph object before creating the adjacency matrix, just plot it.
plot(G)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Networks에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by