I have an adjacency matrix .Now I want to rewire by replacing two edges at random.

1 次查看(过去 30 天)
clc;
clear all;
n = 10;
C= zeros(n, n);
C(1,n)=1;
C(1,n-1)=1;
C(2,n)=1;
A = zeros(n, n);
for i = 1:n
for j = 1:n
if j==i+1 || j == i + 2
A(i,j) = 1;
else
A(i, j) = 0;
end
end
end
B1=A+C;
B=B1+B1';

回答(1 个)

Aastha
Aastha 2025-5-8
Hi @mks,
As I understand, you would like to rewire the graph represented by an adjacency matrix by replacing two existing edges with two new random edge i.e., remove two existing edges from the graph and insert two new ones, so that the total number of edges remains the same.
In the attached code, the matrix "B" represents an adjacency matrix. Each entry "B(i,j) = 1" indicates the presence of an edge between nodes "i" and "j", and "B(i,j) = 0" indicates no edge. The matrix "B" is symmetric because, in the last line of code, you have defined it as "B = B1 + B1'", which ensures symmetry.
To rewire the graph by replacing two edges at random, you may refer to the following steps:
1. First, find all existing edges using the upper triangular part of the adjacency matrix "B" to avoid duplicates. You can use the "triu" and "find" functions in MATLAB, which convert the matrix into an upper triangular form and find the elements that are 1 in that matrix, respectively:
[i_idx, j_idx] = find(triu(B));
For more information on the "find" and "triu" functions, refer to the MathWorks documentation links
2. Next, select two random edges to remove from the list of edges. This can be done by generating a random index using the "randperm" function in MATLAB and selecting the corresponding edges. Refer to the code snippet below:
num_edges = length(i_idx);
perm = randperm(num_edges, 2);
edge1 = [i_idx(perm(1)), j_idx(perm(1))];
edge2 = [i_idx(perm(2)), j_idx(perm(2))];
For more information on the "randperm" function, you may refer to the MathWorks documentation link mentioned below:
3. Remove the selected edges from the adjacency matrix. You may refer to the MATLAB code given below to do so:
B(edge1(1), edge1(2)) = 0;
B(edge1(2), edge1(1)) = 0;
B(edge2(1), edge2(2)) = 0;
B(edge2(2), edge2(1)) = 0;
4. Finally, add two new random edges, ensuring they don’t already exist. You can find the zero elements in the upper triangular part of "B", excluding the diagonal entries.
I hope this helps!

类别

Help CenterFile Exchange 中查找有关 Networks 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by