Created
January 6, 2021 11:03
-
-
Save johnlees/16af4a4987e4e3be83d86a4f57fbc30f to your computer and use it in GitHub Desktop.
Matrix power in base R using exponentiation by squaring
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
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