how can i create a graph by selecting random edges in a set of given edges?

1 回表示 (過去 30 日間)
Krishna Bezawada
Krishna Bezawada 2016 年 4 月 18 日
回答済み: BhaTTa 2024 年 9 月 9 日
hi, i need to create an graph with edges=10 and nodes=5, since i can have 1024 different combinations with out selfloops, how can i generate a graph by selecting random edges

回答 (1 件)

BhaTTa
BhaTTa 2024 年 9 月 9 日
@Krishna Bezawada, to generate a graph with 5 nodes and 10 edges in MATLAB, you can use the graph function. Since you want to randomly select edges without self-loops, you can follow these steps:
  1. Generate all possible edges without self-loops for a graph with 5 nodes.
  2. Randomly select 10 edges from these possible edges.
  3. Create the graph using the selected edges.
Here's a MATLAB script to accomplish this:
% Number of nodes and edges
numNodes = 5;
numEdges = 10;
% Generate all possible edges without self-loops
allEdges = nchoosek(1:numNodes, 2); % Combinations of two nodes
% Check the number of possible edges
numPossibleEdges = size(allEdges, 1);
% Ensure that the number of edges is feasible
if numEdges > numPossibleEdges
error('The number of edges exceeds the possible number without self-loops.');
end
% Randomly select edges
selectedEdgesIdx = randperm(numPossibleEdges, numEdges);
selectedEdges = allEdges(selectedEdgesIdx, :);
% Create and plot the graph
G = graph(selectedEdges(:, 1), selectedEdges(:, 2));
% Plot the graph
figure;
plot(G);
title('Randomly Generated Graph');

カテゴリ

Help Center および File ExchangeGraph and Network Algorithms についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by