- 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.
How to create a random adjacency matrix with a changeable degree and number of players using only for-loops, and if-statements?
15 次查看(过去 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.
0 个评论
回答(1 个)
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 -
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
Regards
Vinayak Luha
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!