在Numpy中将矩阵乘以另一个矩阵的每行

b4wnujal  于 2023-11-18  发布在  其他
关注(0)|答案(4)|浏览(119)

我有一个齐次变换矩阵,大小为(4x4),轨迹大小为(nx3),轨迹的每一行都是一个向量。
我想用齐次变换矩阵乘以每一行轨迹。下面是代码:

#append zero column at last
trajectory = np.hstack((trajectory, np.zeros((trajectory.shape[0], 1)))) #(nx3)->(nx4)

trajectory_new = np.zeros((1, 3)) #(1x3)
for row in trajectory:
    vect = row.reshape((-1,1)) #convert (1x4) to (4x1)
    vect = np.dot(HTM, vect) #(4x4) x (4x1) = (4x1)
    vect = vect.T #(1x4)
    vect = np.delete(vect, -1, axis=1) #remove last element from vector
    trajectory_new = np.vstack((trajectory_new, vect)) #(nx3)

trajectory_new = np.delete(trajectory_new, 0, axis=0)#remove first row

字符串
上面的代码工作.然而,我正在寻找更简单的解决方案,如以下:

trajectory_new = np.apply_along_axis(np.multiply, 0, trajectory, HTM)


任何帮助,请。

回答:

trajectory = np.hstack((trajectory, np.ones((trajectory.shape[0], 1))))#(nx3)->(nx4)
trajectory_new = trajectory.dot(HTM.T)[:,:-1]

3okqufwl

3okqufwl1#

你能提供一个输入和输出的例子吗?但似乎np.dot(HTM, trajectory.T)[:3].T可以做到这一点?
为什么不删除HTM的最后一行,而不是在trajectory上追加一列0?

vuktfyat

vuktfyat2#

我想你想要的是:

trajectory_new = np.einsum('ij,kj->ik', HTM[:,:3], trajectory)

字符串
不确定顺序,但应该比for循环快得多

r55awzrz

r55awzrz3#

在堆叠zeros之前,您可以简单地在输入上使用np.dot的矩阵乘法-

trajectory.dot(HTM[:,:3].T)[:,:3]

字符串
方法-

def dot_based(trajectory):
    return trajectory.dot(HTM[:,:3].T)[:,:3]

def original_app(trajectory):
    # append zero column at last
    traj_stacked = np.hstack((trajectory, np.zeros((trajectory.shape[0], 1))))

    trajectory_new = np.zeros((1, 3)) #(1x3)
    for row in traj_stacked:
        vect = row.reshape((-1,1)) #convert (1x4) to (4x1)
        vect = np.dot(HTM, vect) #(4x4) x (4x1) = (4x1)
        vect = vect.T #(1x4)
        vect = np.delete(vect, -1, axis=1) #remove last element from vector
        trajectory_new = np.vstack((trajectory_new, vect)) #(nx3)

    trajectory_new = np.delete(trajectory_new, 0, axis=0)#remove first row
    return trajectory_new


样品运行-

In [37]: n = 5
    ...: trajectory = np.random.rand(n,3)
    ...: HTM = np.random.rand(4,4)
    ...: 

In [38]: np.allclose(dot_based(trajectory), original_app(trajectory))
Out[38]: True

qfe3c7zg

qfe3c7zg4#

你的轨迹是nx3,但是为了正确地相乘,你需要3xn。因此你需要转置两次。一次在相乘之前,一次在相乘之后。
像这样,

trajectory = (HTM[:3,:3] @ trajectory.T).T

字符串
我假设轨迹是一个向量,你想忽略HTM的原点?如果你也想加上原点,那么你可以这样做。

trajectory = (HTM[:3,:3] @ trajectory.T).T + HTM[:3,3]

相关问题