将矩阵提高到n次方

时间:2018-09-25 03:31:08

标签: python python-3.x numpy matrix-multiplication multiplication

我正在尝试将矩阵自身相乘n次

import numpy as np
fil1=3
col1=2

mat1 = random.random((fil1,col1))
mat3 = np.zeros((fil1,col1))
pot = 3
print('Matriz A:\n',mat1) 
for r in range(0,fil1):
    for c in range (0,col1):
        mat3[r,c]=mat1[r,c]*mat1[r,c]
print('Pot:\n',mat3)

如何通过将同一矩阵乘以n来实现它?

#Example Mat1^2 = 
[ 1  2  3     [ 1  2  3       [ 1  2  3       [ 30  36  42 
  4  5  6   =   4  5  6    *    4  5  6     =   66  81  96
  7  8  9 ]     7  8  9 ]       7  8  9 ]       102 126 150 ]

1 个答案:

答案 0 :(得分:0)

您可以使用numpy.matmul创建自己的递归函数:

import numpy as np

a = [[1,2,3], [4,5,6], [7,8,9]];

def matrixMul(a, n):
    if(n <= 1):
        return a
    else:
        return np.matmul(matrixMul(a, n-1), a)

print(matrixMul(a, 4))

使用 for循环的非递归方式:

import numpy as np
a = [[1,2,3], [4,5,6], [7,8,9]];

def matrixMul(a, n):
    if(n == 1):
        return a
    else:
            tempArr = a;
            for i in range(1, n-1):
                tempArr = np.matmul(a, tempArr)
            return tempArr

print(matrixMul(a, 4))