Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a specific matrix in R

Tags:

r

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.

like image 534
MOHAMMED Avatar asked Jan 19 '26 00:01

MOHAMMED


2 Answers

  1. Create a matrix with 0 values
  2. Subtract row index with column index.
  3. Replace values in matrix with 1 where the difference is 1 or -1
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
like image 132
Ronak Shah Avatar answered Jan 21 '26 13:01

Ronak Shah


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

like image 33
ThomasIsCoding Avatar answered Jan 21 '26 13:01

ThomasIsCoding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!