矩阵本身求幂 N 次?

Ped*_*dro 6 python numpy exponentiation matrix-multiplication python-3.x

我正在使用 FOR 实现矩阵求幂:

import numpy as np
fl=2
cl=2
fl2=fl
cl2=cl
M = random.random((fl,cl))
M2 = M
Result = np.zeros((fl,cl))
Temp = np.zeros((fl,cl))
itera = 2
print('Matriz A:\n',M)
print('Matriz AxA:\n',M2)

for i in range (0,itera):
    for a in range(0,fl):
        for b in range (0,cl):  
            Result[a,b]+=M[a,b]*M[a,b]
            temp[a,b]=Result[a,b]
            Res[a,k]=M[a,b]
print('Potencia:\n',temp)
print('Matriz:\n', Result)
Run Code Online (Sandbox Code Playgroud)

错误在于它不能很好地执行乘法,Result[a,b]+=M[a,b]*M[a,b]并且当我将其保存在临时矩阵中以将其与原始矩阵相乘时,它不会进行下一次跳转for i in range (0,itera):

我知道我可以执行该功能np.matmul ,但我尝试使用 FOR 循环来执行该功能

例子

use*_*203 6

您正在寻找np.linalg.matrix_power

如果您正在使用numpy,请不要使用 for 循环,而应使用向量化运算。

arr = np.arange(16).reshape((4,4))

np.linalg.matrix_power(arr, 3)
Run Code Online (Sandbox Code Playgroud)

array([[ 1680,  1940,  2200,  2460],
       [ 4880,  5620,  6360,  7100],
       [ 8080,  9300, 10520, 11740],
       [11280, 12980, 14680, 16380]])
Run Code Online (Sandbox Code Playgroud)

这与显式乘法相同:

arr @ arr @ arr
Run Code Online (Sandbox Code Playgroud)
>>> np.array_equal(arr @ arr @ arr, np.linalg.matrix_power(arr, 3))
True
Run Code Online (Sandbox Code Playgroud)

既然你问了

如果您确实想要一个使用循环的简单解决方案,我们可以很容易地将各个部分组合在一起。首先我们需要一种方法来实际乘以矩阵。有一些选项可以击败 n^3 的复杂性,但这个答案不会这样做。这是一个基本的矩阵乘法函数:

def matmultiply(a, b):
  res = np.zeros(a.shape)
  size = a.shape[0]

  for i in range(size):
    for j in range(size):
      for k in range(size):
        res[i][j] += a[i][k] * b[k][j]

  return res
Run Code Online (Sandbox Code Playgroud)

现在您需要一个指数函数。该函数采用一个矩阵和一个幂,并将矩阵求该幂。

def loopy_matrix_power(a, n):
  res = np.identity(a.shape[0])
  while n > 0:
    if n % 2 == 0:
      a = matmultiply(a, a)
      n /= 2
    else:
      res = matmultiply(res, a)
      n -= 1

  return res
Run Code Online (Sandbox Code Playgroud)

行动中:

loopy_matrix_power(arr, 3)
Run Code Online (Sandbox Code Playgroud)

array([[ 1680.,  1940.,  2200.,  2460.],
       [ 4880.,  5620.,  6360.,  7100.],
       [ 8080.,  9300., 10520., 11740.],
       [11280., 12980., 14680., 16380.]])
Run Code Online (Sandbox Code Playgroud)

  • @佩德罗为什么?这与你想要用 numpy 做的相反 (2认同)