Compute the \(k\)-th power of a matrix. Whereas x^k computes element wise powers, x %^% k corresponds to \(k - 1\) matrix multiplications, x %*% x %*% ... %*% x.

x %^% k

Arguments

x

a square matrix.

k

an integer, \(k \ge 0\).

Details

Argument \(k\) is coerced to integer using as.integer.

The algorithm uses \(O(log_2(k))\) matrix multiplications.

Value

A matrix of the same dimension as x.

Author

Based on an R-help posting of Vicente Canto Casasola, and Vincent Goulet's C implementation in actuar.

Note

If you think you need x^k for \(k < 0\), then consider instead solve(x %^% (-k)).

See also

%*% for matrix multiplication.

Examples

A <- cbind(1, 2 * diag(3)[,-1])
A
#>      [,1] [,2] [,3]
#> [1,]    1    0    0
#> [2,]    1    2    0
#> [3,]    1    0    2
A %^% 2
#>      [,1] [,2] [,3]
#> [1,]    1    0    0
#> [2,]    3    4    0
#> [3,]    3    0    4
stopifnot(identical(A, A %^% 1),
          A %^% 2 == A %*% A)