Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a square matrix such that each element is equal to 2^|j-k| in R

Tags:

r

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))}
}
like image 602
Btzzzz Avatar asked Dec 31 '22 02:12

Btzzzz


2 Answers

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))
like image 104
dvd280 Avatar answered May 12 '23 18:05

dvd280


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
like image 21
IceCreamToucan Avatar answered May 12 '23 16:05

IceCreamToucan