How to create a random adjacency matrix with a changeable degree and number of players using only for-loops, and if-statements?

11 ビュー (過去 30 日間)
clear all
clc
d=2
n=10;
A = zeros(n,n); % Create initial matrix
for i = 1:n
for j = 1:n
if sum(A(i,:))==d || sum(A(:,i))==d
MAKE OTHER ENTRIES IN ROW/COLUMN ZERO AND GO TO NEXT ROW/COLUMN
elseif i==j
A(i,j)=0; % Zero values in the diagonal entries
else
A(i,j)=round(rand); % Choosing random 0 and 1 values
A(j,i)=A(i,j); % Make A matrix symmetric
end
end
end
Currently I am working on a code that needs the random creation of an adjacency matrix. As can be seen in the code, I still need some working lines for the definition of the (changeable) degree of the network. If the degree of the network is 2, every row can have a maximum of two 1's. The same applies for the columns since all players in the network have a maximum of 2 neighbors. How can I do this for variable degrees and players in this code without making a whole new script? Preferably only using for-loops and if-statements.

回答 (1 件)

VINAYAK LUHA
VINAYAK LUHA 2023 年 9 月 22 日
Hi Thijmen,
I understand that you want to create a random adjacency matrix of degree “d” and dimension nxn. In your present setting the time complexity would be o(n^3) however with slight optimization you can achieve the task in o(n^2).
Here’s how to achieve that -
  • Keep two counter arrays to keep count of number of ones in respective rows and columns
  • Traverse the lower triangular matrix and set the value of an entry based on some threshold applied on value drawn from uniform probability distribution.
  • Make the matrix symmetric
  • Update the respective counters for columns and rows.
Here’s the code for your reference-
n=8;
d=3; %d should be valid, i.e d<10
adj =zeros(n,n);
zcRows =zeros(1,n);
zcCols =zeros(1,n);
for i=1:n
for j=1:n
if(i<j)
if(zcRows(i)<d &&zcCols(j)<d)
adj(i,j)=(rand()>0.5);
adj(j,i)=adj(i,j);
zcRows(i)=zcRows(i)+adj(i,j);
zcCols(j)=zcCols(j)+adj(i,j);
zcRows(j)=zcRows(j)+adj(j,i);
zcCols(i)=zcCols(i)+adj(j,i);
end
end
end
end
adj
adj = 8×8
0 0 1 1 1 0 0 0 0 0 1 1 1 0 0 0 1 1 0 1 0 0 0 0 1 1 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 0
Regards
Vinayak Luha

カテゴリ

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