Skip to content

Instantly share code, notes, and snippets.

@bschneidr
Last active October 28, 2022 12:33
Show Gist options
  • Select an option

  • Save bschneidr/05d4855231439ed43adb5251c7560749 to your computer and use it in GitHub Desktop.

Select an option

Save bschneidr/05d4855231439ed43adb5251c7560749 to your computer and use it in GitHub Desktop.
Expresses sample variance as a quadratic form
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