[英]Python 3: Multiply a vector by a matrix without NumPy
我對 Python 相當陌生,並試圖創建一個函數來將向量乘以矩陣(任何列大小)。 例如:
multiply([1,0,0,1,0,0], [[0,1],[1,1],[1,0],[1,0],[1,1],[0,1]])
[1, 1]
這是我的代碼:
def multiply(v, G):
result = []
total = 0
for i in range(len(G)):
r = G[i]
for j in range(len(v)):
total += r[j] * v[j]
result.append(total)
return result
問題是,當我嘗試選擇矩陣 (r[j]) 中每列的第一行時,會顯示錯誤“列表索引超出范圍”。 有沒有其他方法可以在不使用 NumPy 的情況下完成乘法?
Numpythonic 方法:(使用numpy.dot
以獲得兩個矩陣的點積)
In [1]: import numpy as np
In [3]: np.dot([1,0,0,1,0,0], [[0,1],[1,1],[1,0],[1,0],[1,1],[0,1]])
Out[3]: array([1, 1])
Pythonic 方法:
你的第二個for
循環的長度是len(v)
並且你試圖基於它對v
進行索引,所以你得到了索引 Error 。 作為一種更pythonic的方式,您可以使用zip
函數來獲取列表的列,然后在列表理解中使用starmap
和mul
:
In [13]: first,second=[1,0,0,1,0,0], [[0,1],[1,1],[1,0],[1,0],[1,1],[0,1]]
In [14]: from itertools import starmap
In [15]: from operator import mul
In [16]: [sum(starmap(mul, zip(first, col))) for col in zip(*second)]
Out[16]: [1, 1]
我認為您的代碼的問題在於您遍歷矩陣的行而不是列。 此外,您不會在每個 vector*matrix 列計算后重置“total”變量。 這就是你想要的:
def multiply(v, G):
result = []
for i in range(len(G[0])): #this loops through columns of the matrix
total = 0
for j in range(len(v)): #this loops through vector coordinates & rows of matrix
total += v[j] * G[j][i]
result.append(total)
return result
我附上了矩陣乘法的代碼,請遵循一維乘法的示例格式(列表列表)
def MM(a,b):
c = []
for i in range(0,len(a)):
temp=[]
for j in range(0,len(b[0])):
s = 0
for k in range(0,len(a[0])):
s += a[i][k]*b[k][j]
temp.append(s)
c.append(temp)
return c
a=[[1,2]]
b=[[1],[2]]
print(MM(a,b))
結果是 [[5]]
r
是來自G
一個元素,所以它是一個只有兩個元素的行。 這意味着您不能使用索引j
從r
獲取值,因為j
從 0 到v
的長度,在您的示例中為 6 。
我需要第一個矩陣可以是二維的解決方案。 擴展@Kasramvd 的解決方案以接受二維first
矩陣。 貼在這里供參考:
>>> first,second=[[1,0,0,1,0,0],[0,1,1,1,0,0]], [[0,1],[1,1],[1,0],[1,0],[1,1],[0,1]]
>>> from itertools import starmap
>>> from operator import mul
>>> [[sum(starmap(mul, zip(row, col))) for col in zip(*second)] for row in first]
[[1, 1], [3, 1]]
有一個代碼可以幫助您將兩個矩陣相乘:
A=[[1,2,3],[4,5,6],[7,8,9]] B=[[1,2,3],[4,5,6],[7,8,9]] matrix=[] def multiplicationLineColumn(line,column): try: sizeLine=len(line) sizeColumn=len(column) if(sizeLine!=sizeColumn): raise ValueError("Exception") res = sum([line[i] * column[i] for i in range(sizeLine)]) return res except ValueError: print("sould have the same len line & column") def getColumn(matrix,numColumn): size=len(matrix) column= [matrix[i][numColumn] for i in range(size)] return column def getLine(matrix,numLine): line = matrix[numLine] return line for i in range(len(A)): matrix.append([]) for j in range(len(B)): matrix[i].append(multiplicationLineColumn(getLine(A,i),getColumn(B,j))) print(matrix)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.