I have an adjacency matrix .Now I want to rewire by replacing two edges at random.I have tried please see below
Show older comments
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';
##
umEdgesToRewire =2;
matrixSize=10;
edgesToRewire = randperm(matrixSize, numEdgesToRewire);
for i = 1:numEdgesToRewire
node1 = edgesToRewire(i);
node2 = randi([1, matrixSize]);
while node2 == node1 || B(node1, node2) == 1
node2 = randi([1, matrixSize]);
end
B(node1, node2) = 1;
B(node2, node1) = 1;
end
Answers (1)
Hello MKS,
It seems you want to rewire an adjacency matrix by removing two random edges and adding two new ones.
Here are the steps to achieve this:
- Use the 'triu' function to obtain the upper triangular part of the matrix. For more information on 'triu' function, refer to this documentation: https://www.mathworks.com/help/matlab/ref/triu.html .
- Use the 'find' function to locate the indexes of non-zero elements. This will assign indexes to each edge in the adjacency matrix. For more information on 'find' function, refer to this documentation: https://www.mathworks.com/help/matlab/ref/find.html .
numEdgesToRewire = 2;
[existingEdgesRow, existingEdgesCol] = find(triu(B));
- Then, use the 'randperm' function to select two edges randomly. More information on this function, is in the documentation: https://www.mathworks.com/help/matlab/ref/randperm.html .
indicesToRemove = randperm(length(existingEdgesRow), numEdgesToRewire);
- The following code snippet can be used to remove the selected edges:
for k = 1:numEdgesToRewire
node1 = existingEdgesRow(indicesToRemove(k));
node2 = existingEdgesCol(indicesToRemove(k));
B(node1, node2) = 0;
B(node2, node1) = 0;
disp(['Removed edge between nodes ' num2str(node1) ' and ' num2str(node2)]);
end
- Use a while loop to find nodes and add new edges, as demonstrated in the code snippet below:
for k = 1:numEdgesToRewire
node1 = randi(n);
node2 = randi(n);
% Check for self-loops or existing edges
while node1 == node2 || B(node1, node2) == 1
node1 = randi(n);
node2 = randi(n);
end
disp(['Adding new edge between nodes ' num2str(node1) ' and ' num2str(node2)]);
B(node1, node2) = 1;
B(node2, node1) = 1;
end
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!