我对 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]
我认为您的代码的问题在于您循环遍历矩阵的行而不是列。此外,在每个向量*矩阵列计算后,您不会重置“总计”变量。这就是你想要的:
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]]
# check matrices
A = [[1,2],[3,4]]
B = [[1,4],[5,6],[7,8],[9,6]]
def custom_mm(A,B):
if len(A[0]) == len(B): # condition to check if matrix multiplication is valid or not. Making sure matrix is nXm and mXy
result = [] # final matrix
for i in range(0,len(A)): # loop through each row of first matrix
temp = [] # temporary list to hold output of each row of the output matrix where number of elements will be column of second matrix
for j in range(0,len(B[0])): # loop through each column of second matrix
total = 0
l = 0 # dummy index to switch row of second matrix
for k in range(0,len(A[0])):
total += A[i][k]*B[l][j]
l = l+1
temp.append(total)
result.append(temp)
return result
else:
return (print("not possible"))
print(custom_mm(A,B))
有一个代码可以帮助你将两个矩阵相乘:
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)