将 (N,N) 矩阵与向量 (V) 相乘,使输出的形状为 (N,N,V)

  • 本文关键字:输出 向量 相乘 python numpy shapes
  • 更新时间 :
  • 英文 :


Hei 在那里 - 我是一个 python 初学者,我想弄清楚以下内容:

我想将形状 (n,n( 的矩阵与形状 (v( 的向量相乘,以便输出具有形状 (n,n,v(。

我的代码看起来像这样,但它远非优雅。

def D(x,y,B,n): 
# shape of x,y is (n,n) # shape of B is (v)
a = np.ndarray(shape = (n,n,1), dtype = float)
b = np.ndarray(shape = (n,n,1), dtype = float)
a = np.arctan2(y, x)*(B[0])/(2.*math.pi)    
b = np.arctan2(y, x)*(B[1])/(2.*math.pi)
c, d = ...
return np.asarray([a,b,c,d]).T

x 和 y 是网格的矩阵,表示半径。

任何帮助都非常感谢!谢谢!!

你可以做: def D(x,y,B,n(: # x,y 的形状是 (n,n( # B 的形状是 (v(

a = np.ndarray(shape = (n,n,1), dtype = float)
b = np.ndarray(shape = (n,n,1), dtype = float)
c = np.arctan2(y, x) * B[None, None, :]
# c.shape == (n, n, v)

return c.T

尝试使用它,这是我所知道的最快的方法

def D(x,y,B,n): 
M = np.arctan2(y, x)          # shape= [n, n]
b = B / (2.*math.pi)          # shape= [v,]
r = M[..., np.newaxis] * b    
return r                      # shape= [n, n, v]

...省略号表示数组的所有轴,np.newaxis添加一个新轴,因此A[..., np.newaxis]一起返回一个形状[n, n, 1]数组

,可以使用b

将形状数组与形状数组广播[n, n, 1][v]生成形状[n, n, v]数组

如果A形状[a, b, c].A[..., np.newaxis]会把它改成[a, b, c, 1]

最新更新