我有一个numpy 2x2矩阵定义如下:
a = np.pi/2
g = np.asarray([[-np.sin(a), -np.cos(a)],
[ np.cos(a), -np.sin(a)]])
现在,我想要使用这个矩阵进行转换的n个数组2D点。因此,我们可以模拟一堆(25)2D点,如下所示:
p = np.random.rand(25, 2)
如何通过广播对所有这25个点进行矩阵向量乘法,而不是进行for
循环?
目前,我可以做类似的事情:
for i in range(25):
print np.dot(g, p[i])
这应该给我另一个形状为(25,2)的2D数组。
如果没有for
循环,有更优雅的方法吗?
答案 0 :(得分:3)
尝试:
np.dot(p, g.T)
将点乘以旋转矩阵的转置。
答案 1 :(得分:3)
我认为你想要的是 -
np.dot(p,g.T)
.T
是转置数组
示例/演示 -
In [1]: import numpy as np
In [2]: a = np.pi/2
In [3]: g = np.asarray([[-np.sin(a), -np.cos(a)],
...: [ np.cos(a), -np.sin(a)]])
In [4]: p = np.random.rand(25, 2)
In [8]: for i in range(25):
...: print(np.dot(g, p[i]))
...:
[-0.56997282 -0.70151323]
[-0.65807814 -0.21773391]
[-0.533987 -0.53936287]
[-0.91982277 -0.01423868]
[-0.96648577 -0.42122831]
[-0.67169383 -0.94959473]
[-0.09013282 -0.57637376]
[-0.03937037 -0.94635173]
[ -2.59523258e-01 -4.04297667e-05]
[-0.77029438 -0.67325988]
[-0.24862373 -0.89806226]
[-0.91866799 -0.07927881]
[-0.83540497 -0.33473515]
[-0.38738641 -0.75406194]
[-0.07569734 -0.66859275]
[-0.72707983 -0.21314985]
[-0.67738699 -0.90763549]
[-0.96172981 -0.68684667]
[-0.40152064 -0.14629421]
[-0.46495457 -0.37456133]
[-0.97915149 -0.0470546 ]
[-0.76488223 -0.70756525]
[-0.21534494 -0.91354898]
[-0.25035908 -0.37841355]
[-0.17990176 -0.18436497]
In [10]: np.dot(p,g.T)
Out[10]:
array([[ -5.69972820e-01, -7.01513225e-01],
[ -6.58078138e-01, -2.17733909e-01],
[ -5.33987004e-01, -5.39362872e-01],
[ -9.19822767e-01, -1.42386768e-02],
[ -9.66485769e-01, -4.21228314e-01],
[ -6.71693832e-01, -9.49594730e-01],
[ -9.01328234e-02, -5.76373760e-01],
[ -3.93703749e-02, -9.46351732e-01],
[ -2.59523258e-01, -4.04297667e-05],
[ -7.70294378e-01, -6.73259882e-01],
[ -2.48623728e-01, -8.98062260e-01],
[ -9.18667987e-01, -7.92788080e-02],
[ -8.35404971e-01, -3.34735152e-01],
[ -3.87386412e-01, -7.54061939e-01],
[ -7.56973425e-02, -6.68592746e-01],
[ -7.27079833e-01, -2.13149846e-01],
[ -6.77386988e-01, -9.07635490e-01],
[ -9.61729810e-01, -6.86846673e-01],
[ -4.01520636e-01, -1.46294211e-01],
[ -4.64954574e-01, -3.74561327e-01],
[ -9.79151491e-01, -4.70545953e-02],
[ -7.64882230e-01, -7.07565246e-01],
[ -2.15344940e-01, -9.13548984e-01],
[ -2.50359076e-01, -3.78413552e-01],
[ -1.79901758e-01, -1.84364974e-01]])