NumCpp  2.11.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
matrix_power.hpp
Go to the documentation of this file.
1 #pragma once
29 
30 #include <string>
31 
34 #include "NumCpp/Core/Shape.hpp"
35 #include "NumCpp/Core/Types.hpp"
36 #include "NumCpp/Functions/dot.hpp"
38 #include "NumCpp/NdArray.hpp"
39 
40 namespace nc::linalg
41 {
42  //============================================================================
43  // Method Description:
59  template<typename dtype>
61  {
63 
64  const Shape inShape = inArray.shape();
65  if (inShape.rows != inShape.cols)
66  {
67  THROW_INVALID_ARGUMENT_ERROR("input matrix must be square.");
68  }
69 
70  if (inPower == 0)
71  {
72  return identity<double>(inShape.rows);
73  }
74 
75  if (inPower == 1)
76  {
77  return inArray.template astype<double>();
78  }
79 
80  if (inPower == -1)
81  {
82  return inv(inArray);
83  }
84 
85  if (inPower > 1)
86  {
87  NdArray<double> inArrayDouble = inArray.template astype<double>();
88  NdArray<double> returnArray = dot(inArrayDouble, inArrayDouble);
89  for (int16 i = 2; i < inPower; ++i)
90  {
91  returnArray = dot(returnArray, inArrayDouble);
92  }
93  return returnArray;
94  }
95 
96  NdArray<double> inverse = inv(inArray);
97  NdArray<double> returnArray = dot(inverse, inverse);
98  inPower *= -1;
99  for (int16 i = 2; i < inPower; ++i)
100  {
101  returnArray = dot(returnArray, inverse);
102  }
103  return returnArray;
104  }
105 } // namespace nc::linalg
#define THROW_INVALID_ARGUMENT_ERROR(msg)
Definition: Error.hpp:37
#define STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype)
Definition: StaticAsserts.hpp:56
const Shape & shape() const noexcept
Definition: NdArrayCore.hpp:4464
A Shape Class for NdArrays.
Definition: Core/Shape.hpp:41
uint32 rows
Definition: Core/Shape.hpp:44
uint32 cols
Definition: Core/Shape.hpp:45
Definition: cholesky.hpp:41
NdArray< double > matrix_power(const NdArray< dtype > &inArray, int16 inPower)
Definition: matrix_power.hpp:60
NdArray< double > inv(const NdArray< dtype > &inArray)
Definition: inv.hpp:54
NdArray< dtype > dot(const NdArray< dtype > &inArray1, const NdArray< dtype > &inArray2)
Definition: dot.hpp:47
std::int16_t int16
Definition: Types.hpp:37