我试图将数组A的每一行乘以另一个数组(B)中的每一行,以获得与前两个数组具有相同行数和列数的len(A)数组。
任何帮助?
pseudo-code
from numpy import *
import numpy as np
def multipar():
A = array( [ (0.1,0.5,0.2,0.2), (0.2,0.5,0.1,0.2), (0.7,0.1,0.1,0.1) ] )
B = array( [ (1,2,3,4), (2,3,4,5), (3,4,5,6) ] )
for i in len(A):
average = A[i]*B
print average
multipar()
我想得到每个新数组
Array C
(0.1,0.5,0.2,0.2) * (1,2,3,4);
(0.1,0.5,0.2,0.2) * (2,3,4,5);
(...)
Array D
(0.2,0.5,0.1,0.2) * (1,2,3,4);
(...)
答案 0 :(得分:2)
你可以用更高的尺寸做一些有趣的事情。将A
或B
扩展到第三维,然后将其与未扩展的维度相乘。
e.g:
A = array( [ (0.1,0.5,0.2,0.2), (0.2,0.5,0.1,0.2), (0.7,0.1,0.1,0.1) ] )
B = array( [ (1,2,3,4), (2,3,4,5), (3,4,5,6) ] )
tiled = tile (B, (3,1,1)).swapaxes (0,1)
all_results = A*tiled
现在,您拥有all_results
中的所有结果数组;您可以使用all_results[0]
,all_results[1]
等轻松获取它们
编辑:回复最新的问题编辑: 如果你真的需要单独的结果数组,那么还有两个选项:
C, D, E = all_results
用我的第一个建议替换最后两个语句:
C = B * A [0]
D = B * A [1]
E = B * A [2]
如果您确实需要单独的数组用于结果,并且需要更多行以便需要循环,那么您可以执行类似的操作(感谢@Jaime用于广播符号)
all_results = A[:, None, :] * B[None, :, :]
for i, res in enumerate (all_results):
locals () ['result%d'%i] = res
现在乘以第一行的结果是名为res1
的变量,res2
中的第二行,依此类推。