【发布时间】:2019-02-28 14:32:26
【问题描述】:
我正在尝试将矩阵自身相乘 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 ]
【问题讨论】:
-
您的问题是什么?你不需要循环。您可以通过
mat1**pot对其进行矢量化 -
我输了,但我正在尝试学习矩阵,我需要应用循环将矩阵相乘 N 次,而不使用 ** @RafaelC
-
确保您了解矩阵乘法(python 中的
M @ M)和逐元素乘法(M * M)之间的区别。 -
顺便说一句。链接二元运算符的通用(在这种情况下不是最佳)方式是
functools.reduce。例如矩阵将M的5个副本相乘:functools.reduce(operator.matmul, 5*[M])。 -
但是如果你想将同一个矩阵相乘N次,它也可以吗? @PaulPanzer
标签: python python-3.x numpy matrix-multiplication multiplication