Is there an easier command to compute vector projection? I am instead using the following:
x = np.array([ 3, -4, 0]) y = np.array([10, 5, -6]) z=float(np.dot(x, y)) z1=float(np.dot(x, x)) z2=np.sqrt(z1) z3=(z/z2**2) x*z3
Advertisement
Answer
Maybe this is what you really want:
np.dot(x, y) / np.linalg.norm(y)
This should give the projection of vector x
onto vector y
– see https://en.wikipedia.org/wiki/Vector_projection. Alternatively, if you want to compute the projection of y
onto x
, then replace y
with x
in the denominator (norm
) of the above equation.
EDIT: As @VaidAbhishek commented, the above formula is for the scalar projection. To obtain vector projection multiply scalar projection by a unit vector in the direction of the vector onto which the first vector is projected. The formula then can be modified as:
y * np.dot(x, y) / np.dot(y, y)
for the vector projection of x
onto y
.