Filter löschen
Filter löschen

Generating a random graph with given average(mean) degree of nodes

6 Ansichten (letzte 30 Tage)
Hyunjin Chung
Hyunjin Chung am 10 Jun. 2022
Beantwortet: Paras Gupta am 14 Sep. 2023
I want to generate a random graph (undirected without self-loop) with input average(mean) degree of nodes.
For example, with given (avg degree = 3 & n = 10), I want to have a randomly generated graph with 10 by 10 adjacency matrix and avg degree of 3.
Can anyone assit me on this please?

Antworten (1)

Paras Gupta
Paras Gupta am 14 Sep. 2023
Hi,
I understand that you want to generate the adjacency matrix for a random undirected graph with an average degree given as input. Please refer to the code below to achieve the same.
adj = generateRandomGraph(10, 3)
adj = 10×10
0 0 1 0 0 0 0 0 1 1 0 0 1 1 1 0 0 1 0 0 1 1 0 1 0 0 0 1 0 1 0 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0 1 1 0 0 1 1 0 1 0 1 0 0 0 0 0 0 1 0 0 1 0 1 0 1 0 1 0 0 0
G = graph(adj);
numNodes = numnodes(G)
numNodes = 10
avgDegree = mean(degree(G))
avgDegree = 3
function adjacencyMatrix = generateRandomGraph(n, avgDegree)
% Create an empty adjacency matrix
adjacencyMatrix = zeros(n, n);
% Calculate the maximum number of edges allowed
maxEdges = n * (n - 1) / 2;
% Calculate the desired number of edges
numEdges = round(n * avgDegree / 2);
% Check if the desired number of edges is valid
if numEdges > maxEdges
error('Invalid average degree. Too high for the number of nodes.');
end
% Generate random edges until reaching the desired number
while numEdges > 0
% Generate two random nodes
node1 = randi(n);
node2 = randi(n);
% Check if the edge already exists or if it's a self-loop
if adjacencyMatrix(node1, node2) == 0 && node1 ~= node2
% Add the edge
adjacencyMatrix(node1, node2) = 1;
adjacencyMatrix(node2, node1) = 1;
% Decrease the number of remaining edges
numEdges = numEdges - 1;
end
end
end
Please refer to the following documentations for more information on the functions used in the code above:
Hope this helps.

Kategorien

Mehr zu Graph and Network Algorithms finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by