Skip to content

Instantly share code, notes, and snippets.

@johnlees
Created January 6, 2021 11:03
Show Gist options
  • Save johnlees/16af4a4987e4e3be83d86a4f57fbc30f to your computer and use it in GitHub Desktop.
Save johnlees/16af4a4987e4e3be83d86a4f57fbc30f to your computer and use it in GitHub Desktop.
Matrix power in base R using exponentiation by squaring
matrix_pow <- function(x, n) {
if (abs(n - round(n)) < .Machine$double.eps^0.5) {
stop(sprintf("Power %.1f is not an integer", n))
}
if (n < 0) {
return(matrix_exp(solve(x), -n))
} else if (n == 0) {
return(1)
} else if (n == 1) {
return(x)
} else if (n %% 2 == 0) {
return(matrix_exp(x %*% x, n / 2))
} else {
return(x %*% matrix_exp(x %*% x, (n - 1) / 2))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment