Hei there - 我是一个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是meshgrid的矩阵,代表半径。
任何帮助是非常感激!
你可以这样做: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]