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