Power
Power
将方阵提升整数幂。
matrix matrix::Power(
const int power // 幂
);参数
- power
[输入] 指数可以是任何整数、正数、负数或零。
返回值
矩阵。
注意
生成的矩阵与原始矩阵的大小相同。 当升幂为 0 时,返回单位矩阵。 正幂 n 表示原始矩阵自身乘以 n 次。 负幂 -n 表示原始矩阵先倒置,然后将倒置矩阵乘以自身 n 次。
以 MQL5 实现的矩阵升幂的简单算法:
bool MatrixPower(matrix& c, const matrix& a, const int power)
{
//--- 矩阵必须是正阵
if(a.Rows()!=a.Cols())
return(false);
//--- 结果矩阵的大小完全相同
ulong rows=a.Rows();
ulong cols=a.Cols();
matrix result(rows,cols);
//--- 当幂为零时,返回单位矩阵
if(power==0)
result.Identity();
else
{
//--- 对于负值,首先反转矩阵
if(power<0)
{
matrix inverted=a.Inv();
result=inverted;
for(int i=-1; i>power; i--)
result=result.MatMul(inverted);
}
else
{
result=a;
for(int i=1; i<power; i++)
result=result.MatMul(a);
}
}
//---
c=result;
return(true);
}MQL5 示例:
matrix i= {{0, 1}, {-1, 0}};
Print("i:\n", i);
Print("i.Power(3):\n", i.Power(3));
Print("i.Power(0):\n", i.Power(0));
Print("i.Power(-3):\n", i.Power(-3));
/*
i:
[[0,1]
[-1,0]]
i.Power(3):
[[0,-1]
[1,0]]
i.Power(0):
[[1,0]
[0,1]]
i.Power(-3):
[[0, -1]
[1,0]]
*/Python 示例:
import numpy as np
from numpy.linalg import matrix_power
# matrix equiv. of the imaginary unit
i = np.array([[0, 1], [-1, 0]])
print("i:\n",i)
# should = -i
print("matrix_power(i, 3) :\n",matrix_power(i, 3) )
print("matrix_power(i, 0):\n",matrix_power(i, 0))
# should = 1/(-i) = i, but w/ f.p. elements
print("matrix_power(i, -3):\n",matrix_power(i, -3))
i:
[[ 0 1]
[-1 0]]
matrix_power(i, 3) :
[[ 0 -1]
[ 1 0]]
matrix_power(i, 0):
[[1 0]
[0 1]]
matrix_power(i, -3):
[[ 0. 1.]
[-1. 0.]]