# strange matrix result from if else loop

user8003788 Source

The code below to fill a matrix with 1 if the vertex is adjacent to another vertex and 0 otherwise. I used this function for comparison but the resulted matrix is strange !!

R
library(igraph)

#prepare random data

random<-matrix(c(1,2,2,3,3,4),ncol=2,byrow=TRUE)
graph<-graph.data.frame(random, directed = FALSE)
v1<-c()
v2<-c()
for (edge in 1:length(E(graph))){
ver1<-ends(graph = graph, es = edge)[1]
v1[edge]<-ver1
ver2<-ends(graph = graph, es = edge)[2]
v2[edge]<-ver2
}
v1
[1] "1" "2" "3"

#Construct the matrix

n1<-matrix(,nrow=length(v1), ncol=length(V(graph)))
for(i in 1:length(v1)){
for(j in 1:length(V(graph))){
if(TRUE){
n1[i,j]<-1
}
else{
n1[i,j]<-0
}
}

}
n1
[,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    1    1    1    1
[3,]    1    1    1    1

While the resulted matrix should be:

n1
[,1] [,2] [,3] [,4]
[1,]    0    1    0    0
[2,]    1    0    1    0
[3,]    0    1    0    1

since 1 is adjacent only to 2, 2 is adjacent to 1 & 3, 3 is adjacent to 2 & 4, 4 is adjacent only to 3

answered 6 months ago thc #1

The error is your if statement:

Try this:

n1<-matrix(,nrow=length(v1), ncol=length(V(graph)))
for(i in 1:length(v1)){
for(j in 1:length(V(graph))){
n1[i,j]<-1
}
else{
n1[i,j]<-0
}
}
}