I want to implement a command in R which generates a nxn matrix A, such that each element aij = 2^|j-k|. I have the below code but I was wondering if there was something more elegant and precise rather than a nested loop?
A = matrix(1, nrow = n, ncol = n)
for (j in 1:n) {
for(k in 1:n) {
A[j,k] <- 2^(abs(j-k))}
}
Assuming j
are rows and k
are columns:
j = row(A)
k = col(A)
A = 2**abs(j - k)
Or you could skip the middle steps:
A = 2**abs(row(A) - col(A))
This is a symmetric toeplitz matrix, so you can use the toeplitz
function
Example starting matrix
n <- 5
A = matrix(1, nrow = n, ncol = n)
Using the toeplitz
function
toeplitz(2^seq(0, n - 1))
# [,1] [,2] [,3] [,4] [,5]
# [1,] 1 2 4 8 16
# [2,] 2 1 2 4 8
# [3,] 4 2 1 2 4
# [4,] 8 4 2 1 2
# [5,] 16 8 4 2 1
Output is equivalent to
2^abs(row(A) - col(A))
# [,1] [,2] [,3] [,4] [,5]
# [1,] 1 2 4 8 16
# [2,] 2 1 2 4 8
# [3,] 4 2 1 2 4
# [4,] 8 4 2 1 2
# [5,] 16 8 4 2 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With