我正在尝试将矩阵自身相乘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 ]
答案 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))