Skip to content

Instantly share code, notes, and snippets.

@alexpghayes
Created January 23, 2020 05:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexpghayes/2fa5b8a334b96f7695870fc93b8bbc5b to your computer and use it in GitHub Desktop.
Save alexpghayes/2fa5b8a334b96f7695870fc93b8bbc5b to your computer and use it in GitHub Desktop.
n <- 50 # number of observations
d <- 4 # number of dimensions
X <- matrix(rnorm(n * d), nrow = n, ncol = d)
covariance_helper <- function(x, y) {
x_centered <- x - mean(x)
y_centered <- y - mean(y)
sum(x_centered * y_centered) / (length(x) - 1)
}
covariance <- function(X) {
result <- matrix(ncol(X) * ncol(X), nrow = ncol(X), ncol = ncol(X))
for (col1 in 1:ncol(X)) {
for (col2 in 1:ncol(X)) {
x <- X[, col1]
y <- X[, col2]
result[col1, col2] <- covariance_helper(x, y)
}
}
result
}
covariance(X)
### check for correctness
all.equal(cov(X), covariance(X))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment