NumCpp  2.18.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
Loading...
Searching...
No Matches
matrix_power.hpp
Go to the documentation of this file.
1
28#pragma once
29
32#include "NumCpp/Core/Shape.hpp"
33#include "NumCpp/Core/Types.hpp"
36#include "NumCpp/NdArray.hpp"
37
38namespace nc::linalg
39{
40 //============================================================================
41 // Method Description:
57 template<typename dtype>
59 {
61
62 const Shape inShape = inArray.shape();
63 if (inShape.rows != inShape.cols)
64 {
65 THROW_INVALID_ARGUMENT_ERROR("input matrix must be square.");
66 }
67
68 if (inPower == 0)
69 {
70 return identity<double>(inShape.rows);
71 }
72
73 if (inPower == 1)
74 {
75 return inArray.template astype<double>();
76 }
77
78 if (inPower == -1)
79 {
80 return inv(inArray);
81 }
82
83 if (inPower > 1)
84 {
85 NdArray<double> inArrayDouble = inArray.template astype<double>();
86 NdArray<double> returnArray = dot(inArrayDouble, inArrayDouble);
87 for (int16 i = 2; i < inPower; ++i)
88 {
89 returnArray = dot(returnArray, inArrayDouble);
90 }
91 return returnArray;
92 }
93
94 NdArray<double> inverse = inv(inArray);
95 NdArray<double> returnArray = dot(inverse, inverse);
96 inPower *= -1;
97 for (int16 i = 2; i < inPower; ++i)
98 {
99 returnArray = dot(returnArray, inverse);
100 }
101 return returnArray;
102 }
103} // namespace nc::linalg
#define THROW_INVALID_ARGUMENT_ERROR(msg)
Definition Error.hpp:37
#define STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype)
Definition StaticAsserts.hpp:56
Holds 1D and 2D arrays, the main work horse of the NumCpp library.
Definition NdArrayCore.hpp:135
const Shape & shape() const noexcept
Definition NdArrayCore.hpp:4587
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 > inv(const NdArray< dtype > &inArray)
Definition inv.hpp:50
NdArray< double > matrix_power(const NdArray< dtype > &inArray, int16 inPower)
Definition matrix_power.hpp:58
std::int16_t int16
Definition Types.hpp:37
NdArray< dtype > dot(const NdArray< dtype > &inArray1, const NdArray< dtype > &inArray2)
Definition dot.hpp:48
NdArray< dtypeOut > astype(const NdArray< dtype > inArray)
Definition astype.hpp:43
NdArray< dtype > identity(uint32 inSquareSize)
Definition identity.hpp:47