[英]multiply a matrix by an integer in 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.')
取決於您對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]])
L=[[1,2],[3,4],[5,6]]
[[elem*3 for elem in row] for row in L]
[[3, 6], [9, 12], [15, 18]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.