Numpy

时间:2017-06-14 07:33:27

标签: python numpy matrix

我有一个大小为(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]

3 个答案:

答案 0 :(得分:1)

你能举一个输入和输出的例子吗?但似乎是这样 np.dot(HTM, trajectory.T)[:3].T可以做到这一点吗?

为什么不删掉trajectory的最后一行,而不是将{0}的一列添加到HTM

答案 1 :(得分:1)

我认为你想要的是:

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

不确定顺序,但这应该比for循环

快得多

答案 2 :(得分:1)

在堆叠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