NumCpp  1.0
A C++ implementation of the Python Numpy library
matrix_power.hpp
Go to the documentation of this file.
1 #pragma once
30 
31 #include "NumCpp/Core/Shape.hpp"
32 #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  else if (inPower == 1)
78  {
79  return inArray.template astype<double>();
80  }
81  else if (inPower == -1)
82  {
83  return inv(inArray);
84  }
85  else 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  else
96  {
97  NdArray<double> inverse = inv(inArray);
98  NdArray<double> returnArray = dot(inverse, inverse);
99  inPower *= -1;
100  for (int16 i = 2; i < inPower; ++i)
101  {
102  returnArray = dot(returnArray, inverse);
103  }
104  return returnArray;
105  }
106  }
107  }
108 }
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:4296
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