Lurcamera
Lurcamera

Reputation: 13

How can I create an arbitrary square matrix in R with elements defined by certain conditions?

I am trying to create a certain (n x n)-matrix in R . The matrix is defined by the following conditions regarding the elements:

Maybe someone can help me with this?

Upvotes: 1

Views: 53

Answers (2)

jay.sf
jay.sf

Reputation: 72613

Just using the diagonals.

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

Upvotes: 2

Allan Cameron
Allan Cameron

Reputation: 173793

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)

Upvotes: 1

Related Questions