domath
domath

Reputation: 202

Writing a matrix in R , by indices

I want to to create this matrix in R, but my codes gives me zero for all elements.

Where the diagonal is 1 and elements adjacent to diagonal is 0.25. enter image description here

n = 97
W =  matrix(0 , n,n)
diag(W)=1
for (i in 1:rowCount) {
  for (j in 1:rowCount){ 
  if(j==i){W[i,j] = 1
  } else if (j==i-1){W[i,j] = .25
  } else if (j==i+1){W[i,j] =.25}
 }}

Upvotes: 0

Views: 28

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

You can use diag to set diagonal elements to 1, and then use row col to set elements adjacent to diagonal as 0.25.

n <- 5
mat <- diag(1, n)
mat[abs(row(mat) - col(mat)) == 1] <- 0.25
mat

#     [,1] [,2] [,3] [,4] [,5]
#[1,] 1.00 0.25 0.00 0.00 0.00
#[2,] 0.25 1.00 0.25 0.00 0.00
#[3,] 0.00 0.25 1.00 0.25 0.00
#[4,] 0.00 0.00 0.25 1.00 0.25
#[5,] 0.00 0.00 0.00 0.25 1.00

Upvotes: 1

Related Questions