Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using python to calculate Vector Projection

Tags:

python

numpy

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
like image 949
Michael Salerno Avatar asked Mar 18 '19 16:03

Michael Salerno


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

like image 139
AGN Gazer Avatar answered Sep 20 '22 20:09

AGN Gazer


The projection of a onto b is defined as

enter image description here

So either

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

or

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

like image 40
Sebastian Nielsen Avatar answered Sep 18 '22 20:09

Sebastian Nielsen