Using Python to Calculate Vector Projection

Using Python to Calculate Vector Projection

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
0

2 Answers

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 . 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.

2

The projection of a onto b is defined as

So either

(np.dot(a, b) / np.dot(b, b)) * b

or

(np.dot(a, b) / np.linalg.norm(b)**2 ) * b

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.