Between covid-19 news and announcements of imminent Russia-Ukraine wars I needed a bit of a distraction. Sooo, here it is how to create an n x n autocorrelation matrix based on a correlation rho
, with a simple 5 x 5 example in R:
n <- 5
rho <- 0.9
mat <- diag(n)
mat <- rho^abs(row(mat) - col(mat))
This produces the following output:
[,1] [,2] [,3] [,4] [,5] [1,] 1.0000 0.900 0.81 0.729 0.6561 [2,] 0.9000 1.000 0.90 0.810 0.7290 [3,] 0.8100 0.900 1.00 0.900 0.8100 [4,] 0.7290 0.810 0.90 1.000 0.9000 [5,] 0.6561 0.729 0.81 0.900 1.0000
How does this work? Starting from defining n as 5, and the basic rho correlation as 0.9, then mat <- diag(n)
creates a diagonal matrix—a square matrix with ones in the diagonal and zeros elsewhere—with 5 rows and 5 columns.