Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply matrix by each row of another matrix in Numpy

I have a homogeneous transformation matrix of size (4x4) and a trajectory of size (nx3). Each row of this trajectory is a vector.

I want to multiply homogeneous transformation matrix by each row of trajectory. Below is the code:

#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

The above code works. However, I am looking for simpler solution, such as following:

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

Any help, please.

Answer:

trajectory = np.hstack((trajectory, np.ones((trajectory.shape[0], 1))))#(nx3)->(nx4)
trajectory_new = trajectory.dot(HTM.T)[:,:-1]
like image 885
Ravi Joshi Avatar asked Sep 11 '25 10:09

Ravi Joshi


1 Answers

Could you include an example of input and output? But it seems that np.dot(HTM, trajectory.T)[:3].T could do the trick?

Rather than appending a column of 0 to trajectory, why don't you drop the last row of HTM?

like image 107
P. Camilleri Avatar answered Sep 12 '25 23:09

P. Camilleri