Automatic Differentiation
 
Loading...
Searching...
No Matches
matrix_power.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_FUN_MATRIX_POWER_HPP
2#define STAN_MATH_PRIM_FUN_MATRIX_POWER_HPP
3
6
7namespace stan {
8namespace math {
9
22template <typename EigMat, require_eigen_t<EigMat>* = nullptr,
23 require_not_vt_var<EigMat>* = nullptr>
24inline Eigen::Matrix<value_type_t<EigMat>, EigMat::RowsAtCompileTime,
25 EigMat::ColsAtCompileTime>
26matrix_power(const EigMat& M, const int n) {
27 using T = value_type_t<EigMat>;
28 constexpr int R = EigMat::RowsAtCompileTime;
29 constexpr int C = EigMat::ColsAtCompileTime;
30
31 check_square("matrix_power", "M", M);
32 check_nonnegative("matrix_power", "n", n);
33 Eigen::Matrix<T, R, C> MM = M;
34 check_finite("matrix_power", "M", MM);
35 if (n == 0)
36 return Eigen::Matrix<T, R, C>::Identity(M.rows(), M.cols());
37 Eigen::Matrix<T, R, C> result = MM;
38 for (int nn = n - 1; nn > 0; nn /= 2) {
39 if (nn % 2 == 1) {
40 result = result * MM;
41 --nn;
42 }
43 MM = MM * MM;
44 }
45 return result;
46}
47
48template <typename EigMat, require_eigen_t<EigMat>* = nullptr>
49inline Eigen::Matrix<value_type_t<EigMat>, EigMat::RowsAtCompileTime,
50 EigMat::ColsAtCompileTime>
51operator^(const EigMat& M, const int n) {
52 return matrix_power(M, n);
53}
54
55} // namespace math
56} // namespace stan
57
58#endif
typename value_type< T >::type value_type_t
Helper function for accessing underlying type.
void check_square(const char *function, const char *name, const T_y &y)
Check if the specified matrix is square.
void check_nonnegative(const char *function, const char *name, const T_y &y)
Check if y is non-negative.
Eigen::Matrix< value_type_t< EigMat >, EigMat::RowsAtCompileTime, EigMat::ColsAtCompileTime > operator^(const EigMat &M, const int n)
plain_type_t< T_m > matrix_power(T_m &&M, const int n)
Returns the nth power of the specific matrix.
void check_finite(const char *function, const char *name, const T_y &y)
Return true if all values in y are finite.
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...