【问题标题】:Multiply matrix by each row of another matrix in Numpy将矩阵乘以 Numpy 中另一个矩阵的每一行
【发布时间】:2017-06-14 07:33:26
【问题描述】:

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

【问题讨论】:

  • 不用堆叠也可以,如this post所示。
  • @Divakar:你说的是this吗?由于形状不匹配,它会出错。请在this 帖子中查看我的评论。
  • 我在谈论我的帖子。我在之前的评论链接中发布的链接。
  • @Divakar:抱歉,但是您已从 HTM 中删除了最后一列,这是不正确的。您可以删除 HTM 的最后一行,但不能删除最后一列。更准确地说,HTM 是 (4x4),其中第一个 (3x3) 表示旋转矩阵,最后一列表示 3D 空间中的平移。 HTM 的最后一行总是 [0, 0, 0, 1],这使得 HTM (4x4) 矩阵。
  • 但是您没有使用 HTM 的最后一列来计算输出 trajectory_new。这就是为什么您需要在开头添加零并使用原始方法删除第一行的原因。

标签: python numpy matrix


【解决方案1】:

您能否提供输入和输出的示例?但似乎 np.dot(HTM, trajectory.T)[:3].T 能做到吗?

与其给trajectory追加一列0,不如去掉HTM的最后一行?

【讨论】:

  • np.dot(HTM, trajectory.T)[:3].T 返回以下错误:shapes (3,4) and (3,5) not aligned: 4 (dim 1) != 3 (dim 0)
【解决方案2】:

我认为你想要的是这样的:

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

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-22
      • 1970-01-01
      • 2019-11-15
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多