I am trying to create a certain (n x n)-matrix in R . The matrix is defined by the following conditions regarding the elements:
a(i,i) = 2 with i = 2,...,n-1
a(1,1) = a(n,n) = 1
a(i,i 1) = a(i,i-1) = -1
a(i,j) = 0 elsewhere
Maybe someone can help me with this?
CodePudding user response:
Just using the diag
onals.
f <- \(n) {
stopifnot(n > 2)
a <- diag(n)
diag(a)[2:(n - 1)] <- 2
diag(a[-1, ]) <- -1
diag(a[, -1]) <- -1
a
}
f(3)
# [,1] [,2] [,3]
# [1,] 1 -1 0
# [2,] -1 2 -1
# [3,] 0 -1 1
f(7)
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,] 1 -1 0 0 0 0 0
# [2,] -1 2 -1 0 0 0 0
# [3,] 0 -1 2 -1 0 0 0
# [4,] 0 0 -1 2 -1 0 0
# [5,] 0 0 0 -1 2 -1 0
# [6,] 0 0 0 0 -1 2 -1
# [7,] 0 0 0 0 0 -1 1
CodePudding user response:
Simple iteration is probably the most straightforward:
make_matrix <- function(size) {
m <- diag(size)
for(i in seq(nrow(m))) {
for(j in seq(ncol(m))) {
if(i == j) m[i,j] <- if(i == 1 || i == size) 1 else 2
else if (j == (i 1) || j == (i - 1)) m[i,j] <- -1
}
}
m
}
make_matrix(4)
#> [,1] [,2] [,3] [,4]
#> [1,] 1 -1 0 0
#> [2,] -1 2 -1 0
#> [3,] 0 -1 2 -1
#> [4,] 0 0 -1 1
make_matrix(10)
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#> [1,] 1 -1 0 0 0 0 0 0 0 0
#> [2,] -1 2 -1 0 0 0 0 0 0 0
#> [3,] 0 -1 2 -1 0 0 0 0 0 0
#> [4,] 0 0 -1 2 -1 0 0 0 0 0
#> [5,] 0 0 0 -1 2 -1 0 0 0 0
#> [6,] 0 0 0 0 -1 2 -1 0 0 0
#> [7,] 0 0 0 0 0 -1 2 -1 0 0
#> [8,] 0 0 0 0 0 0 -1 2 -1 0
#> [9,] 0 0 0 0 0 0 0 -1 2 -1
#> [10,] 0 0 0 0 0 0 0 0 -1 1
Created on 2022-06-18 by the reprex package (v2.0.1)