Vector projection using Python

Vector — it is a geometric object that has both magnitude (that is, length) and direction. The vector is usually represented by a line segment with a specific direction connecting the start point A and the end point B, as shown in the figure below, and is denoted as

Projection of a vector onto another vector

Projection of a vector to another vector given as

Calculate vector projection onto another vector in Python:

# import numpy to perform vector operations

import numpy as np

 

u = np.array ([ 1 , 2 , 3 ])  # vector you

v = np .array ([ 5 , 6 , 2 ])  # vector v:

 
# Problem: Project vector u on vector v

 
# find the norm of the vector v

v_norm = np. sqrt ( sum (v * * 2 )) 

 
# Apply the formula as above
# to project the vector onto another vector
# find point product using np.dot ()

proj_of_u_on_v = (np.dot (u, v) / v_norm * * 2 ) * v

 

print ( " Projection of Vector u on Ve ctor v is: " , proj_of_u_on_v)

Exit:

 Projection of Vector u on Vector v is: [1.76923077 2.12307692 0.70769231] 

One line code to project a vector onto another vector:

(np.dot (u, v) / np.dot (v, v)) * v

Vector projection onto plane

Vector projection the plane is calculated by subtracting the component which is orthogonal plane from ,

where, is a flat normal vector .

Calculate vector projection on a plane in Python:

# import numpy to perform vector operations

import numpy as np

  
# vector you

u = np.array ([ 2 , 5 , 8 ]) 

 
# vector n: n - ortho gonal vector to plane P

n = np.array ([ 1 , 1 , 7 ]) 

  
# Problem: Project vector u on the P plane

  
# find the norm of the vector n

n_norm = np.sqrt ( sum (n * * 2 )) 

 
# Apply the formula as above
# for project vector to orthogonal vector n
# find point product using np.dot ()

proj_of_u_on_n = (np.dot (u, n) / n_norm * * 2 ) * n

 
# subtract from you proj_of_u_on_n:
# this is your projection onto the P plane

print ( "Projection of Vector u on Plane P is:" , u - proj_of_u_on_n)

Output:

 Projecti on of Vector u on Plane P is: [0.76470588 3.76470588 -0.64705882]