Python 3:在没有 NumPy 的情况下将向量乘以矩阵
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28253102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python 3: Multiply a vector by a matrix without NumPy
提问by JGraham353
I'm fairly new to Python and trying to create a function to multiply a vector by a matrix (of any column size). e.g.:
我对 Python 相当陌生,并试图创建一个函数来将向量乘以矩阵(任何列大小)。例如:
multiply([1,0,0,1,0,0], [[0,1],[1,1],[1,0],[1,0],[1,1],[0,1]])
[1, 1]
Here is my code:
这是我的代码:
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
The problem is that when I try to select the first row of each column in the matrix (r[j]) the error 'list index out of range' is shown. Is there any other way of completing the multiplication without using NumPy?
问题是,当我尝试选择矩阵 (r[j]) 中每列的第一行时,会显示错误“列表索引超出范围”。有没有其他方法可以在不使用 NumPy 的情况下完成乘法?
采纳答案by Kasramvd
The Numpythonic approach: (using numpy.dot
in order to get the dot product of two matrices)
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])
The Pythonic approach:
Pythonic 方法:
The length of your second for
loop is len(v)
and you attempt to indexing v
based on that so you got index Error . As a more pythonic way you can use zip
function to get the columns of a list then use starmap
and mul
within a list comprehension:
您的第二个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]
回答by Simeon Visser
r
is an element from G
so it's a row which only has two elements. That means you can't use index j
to get a value from r
because j
goes from 0 till the length of v
, which is 6 in your example.
r
是一个元素 fromG
所以它是一个只有两个元素的行。这意味着您不能使用 indexj
从中获取值,r
因为j
从 0 到 的长度v
,在您的示例中为 6。
回答by ChrisFreeman
I needed solution where the first matrix could be 2-dimensional. Extending the solution from @Kasramvd to accept a two dimensional first
matrix. Posted here for reference:
我需要第一个矩阵可以是二维的解决方案。扩展来自@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]]
回答by stackPusher
I think the problem with your code was that you loop through the rows of the matrix rather than by the columns. Also you don't reset your 'total' variable after each vector*matrix column calculation. This is what you want:
我认为您的代码的问题在于您遍历矩阵的行而不是列。此外,您不会在每个 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
回答by Pradeep Padmanaban
i have attached a code for matrix multiplication do follow the example format for one dimensional multiplication (lists of list)
我附上了矩阵乘法的代码,请遵循一维乘法的示例格式(列表列表)
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))
result is [[5]]
结果是 [[5]]
回答by Ilyas Maamri
There is a code that help u to multiply two matrix:
有一个代码可以帮助您将两个矩阵相乘:
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)
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)