Search code examples
radjacency-matrix

How to create an adjacency matrix based on a condition in R?


I came across the Q&A: Possible-clique-numbers-of-a-regular-graph.

I have a vec vector and I need to create a adjacency matrix A such that A[i,j]=1 if i−j mod n is an element of vec and A[i,j]=0 otherwise.

My attempt:

k   <- 4
n   <- 10
vec <- c(seq(-k+1, -1), seq(1, k+1))

A <- matrix(0, n, n)

for (i in 1:n)
for (j in 1:n)
A[i,j] <- if((i - j) %% n in vec) 1

I get this error:

Error: unexpected 'in' in:
"for (j in 1:n)
A[i,j] <- if((i - j) %% n in"

Question: how to create an (n x n)-adjacency matrix based on the condition?

Expected result is:

enter image description here


Solution

  • Try this.

    k   <- 4
    n   <- 10
    vec <- c(seq(1, k-1), seq(n-k+1, n-1))  # changed
    
    A <- matrix(0, n, n)
    for (i in 1:n) for (j in 1:n)  A[i,j] <- (abs(i-j%%n)) %in% vec # changed