在Python中用整数乘以矩阵
我知道怎么在一个类里面把两个矩阵相乘。下面我展示了我的代码。不过,我就是搞不懂怎么在Python里把一个矩阵和一个整数相乘。
更新:
这是一个矩阵的例子。
L=[[1,2],[3,4],[5,6]]
3*L
# [[1,6],[9,12],[15,18]]
def __mul__(self,other):
'''this will multiply two predefined matrices where the number of
columns in the first is equal to the number of rows in the second.'''
L=self.L
L2=other.L
result=[]
if len(L[0])==len(L2):
for i in range(len(L)):
row=[]
for j in range(len(L2[0])):
var=0
for k in range(len(L2)):
var=var+L[i][k]*L2[k][j]
row=row+[var]
result = result+[row]
return matrix(result)
else:
raise ValueError('You may not only multiply m*n * n*q matrices.')
2 个回答
0
L=[[1,2],[3,4],[5,6]]
[[elem*3 for elem in row] for row in L]
[[3, 6], [9, 12], [15, 18]]
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
5
这要看你说的matrix
是什么意思,不过如果用numpy的话,可以这样做:
import numpy as np
M= np.arange(9).reshape(3, 3)
# array([[0, 1, 2],
# [3, 4, 5],
# [6, 7, 8]])
2* M
# array([[ 0, 2, 4],
# [ 6, 8, 10],
# [12, 14, 16]])
或者
M= np.matrix([[1, 2], [3, 4]])
# matrix([[1, 2],
# [3, 4]])
2* M
# matrix([[2, 4],
# [6, 8]])