在Numpy中将矩阵乘以另一个矩阵的每一行 [英] Multiply matrix by each row of another matrix in Numpy
本文介绍了在Numpy中将矩阵乘以另一个矩阵的每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将均匀变换矩阵乘以轨迹的每一行.下面是代码:
#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]
解决方案
您可以简单地将矩阵乘法与 解决方案
You can simply use matrix-multiplication with np.dot
on the input before stacking zeros
-
trajectory.dot(HTM[:,:3].T)[:,:3]
Approaches -
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
Sample run -
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
这篇关于在Numpy中将矩阵乘以另一个矩阵的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文