Search code examples
radjacency-matrix

r removing symmetrical elements of a matrix


I'm trying to combine two adjacency matrices leaving out the symmetric intersections.

    M1<-matrix(c(0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0),nrow=5,ncol=5,byrow=T)
    M2<-matrix(c(0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0),nrow=5,ncol=5,byrow=T)

The question is : how to reach the matrix below which "forgets" ([1,2],[2,1]) and displays only ones and zeros ?

My final result should be :

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

I've tried all sorts of additions and substractions involving t(M2) but there is always something wrong.


Solution

  • M = M1+M2
    M[M==t(M)]=0
    +(M>0)
         [,1] [,2] [,3] [,4] [,5]
    [1,]    0    0    0    0    0
    [2,]    0    0    0    0    0
    [3,]    1    0    0    0    0
    [4,]    1    0    0    0    1
    [5,]    0    0    0    0    0