Created
January 23, 2020 05:15
-
-
Save alexpghayes/2fa5b8a334b96f7695870fc93b8bbc5b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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