Creating an n x n autocorrelation matrix

Walking around in old Lisbon.

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:

This produces the following output:

A 5 x 5 autocorrelation matrix

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.

Diagonal matrix

Looking at the final line of code, we have that row(mat) and col(mat) create matrices with the row or col coordinates for each location:

Output of the row() and col() functions

Then abs(row(mat) - col(mat)) is telling us how far is each cell in the matrix from the diagonal. We use that distance as an exponent for rho (0.9 in our example).

Distances from the diagonal

Putting it all together, rho^abs(row(mat) - col(mat)) produces:

n x n autocorrelation matrix

Leave a comment

Your email address will not be published.