It is supposed to make an n x n matrix with 2's along its diagonal and -1 on the first upper and lower diagonal.
M <- function(n){ m <- diag(x = 2, ncol = n, nrow = n) i <- 1 for(i in 1:n-1){ a <- i b <- i + 1 m[a, b] <- -1 m[b, a] <- -1 i <- i + 1 } return(m) } it returns for example with n = 5, a 5 x 5 matrix
M(5) [,1] [,2] [,3] [,4] [,5] [1,] 2 -1 0 0 0 [2,] -1 2 -1 0 0 [3,] 0 -1 2 -1 0 [4,] 0 0 -1 2 -1 [5,] 0 0 0 -1 2 I would like my function to return the same thing but without the for-loop.
nrather than a single value? It's unclear what your desired result is here.Vectorize(M)(5:6)1:n-1. Do you intend for that to be(1:n)-1(starting at 0) or1:(n-1)(starting at 1)?