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

6 次查看(过去 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';
##
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

回答(1 个)

Tejas
Tejas 2024-9-25
编辑:Tejas 2024-9-25
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:
numEdgesToRewire = 2;
[existingEdgesRow, existingEdgesCol] = find(triu(B));
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

产品

Community Treasure Hunt

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

Start Hunting!

Translated by