I want to create the following matrix
A <- matrix(0,n,n)
for(i in 1:n){
for(j in 1:n){
if(abs(i - j) == 1) A1[i,j] <- 1
}
}
Is there another way to create such a matrix? I just want to avoid using for-loop.
n <- 5
A <- matrix(0,n,n)
inds <- row(A) - col(A)
A[abs(inds) == 1] <- 1
A
# [,1] [,2] [,3] [,4] [,5]
#[1,] 0 1 0 0 0
#[2,] 1 0 1 0 0
#[3,] 0 1 0 1 0
#[4,] 0 0 1 0 1
#[5,] 0 0 0 1 0
where row(A) - col(A) (inds) returns :
inds
# [,1] [,2] [,3] [,4] [,5]
#[1,] 0 -1 -2 -3 -4
#[2,] 1 0 -1 -2 -3
#[3,] 2 1 0 -1 -2
#[4,] 3 2 1 0 -1
#[5,] 4 3 2 1 0
A simple option is using outer + abs
> +(abs(outer(1:n,1:n,`-`))==1)
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 0 1 0 0 0 0 0
[2,] 1 0 1 0 0 0 0
[3,] 0 1 0 1 0 0 0
[4,] 0 0 1 0 1 0 0
[5,] 0 0 0 1 0 1 0
[6,] 0 0 0 0 1 0 1
[7,] 0 0 0 0 0 1 0
where n <- 7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With