Last active
October 28, 2022 12:33
-
-
Save bschneidr/05d4855231439ed43adb5251c7560749 to your computer and use it in GitHub Desktop.
Expresses sample variance as a quadratic form
This file contains hidden or 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 = 5 | |
| # Establish quadratic form | |
| quad_form_matrix <- matrix(nrow = n, ncol = n) | |
| for (i in seq(n)) { | |
| for (j in seq(n)) { | |
| if (i == j) { | |
| quad_form_matrix[i,j] <- (1/n) | |
| } else { | |
| quad_form_matrix[i,j] <- -1/((n*(n-1))) | |
| } | |
| } | |
| } | |
| # Calculate sample variance using usual formula ---- | |
| ##_ Single variable | |
| y <- rnorm(n = n) | |
| var(y) | |
| t(y) %*% quad_form_matrix %*% y | |
| ##_ Multiple variables | |
| Y_mat <- MASS::mvrnorm(n = n, mu = c(1,5), Sigma = diag(2)) | |
| t(Y_mat) %*% quad_form_matrix %*% Y_mat | |
| cov(Y_mat) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment