How may I project vectors onto a plane defined by its orthogonal vector in Python?

10,344

Take (d, e, f) and subtract off the projection of it onto the normalized normal to the plane (in your case (a, b, c)). So:

v = (d, e, f)
        - sum((d, e, f) *. (a, b, c)) * (a, b, c) / sum((a, b, c) *. (a, b, c))

Here, by *. I mean the component-wise product. So this would mean:

sum([x * y for x, y in zip([d, e, f], [a, b, c])])

or

d * a + e * b + f * c

if you just want to be clear but pedantic

and similarly for (a, b, c) *. (a, b, c). Thus, in Python:

from math import sqrt

def dot_product(x, y):
    return sum([x[i] * y[i] for i in range(len(x))])

def norm(x):
    return sqrt(dot_product(x, x))

def normalize(x):
    return [x[i] / norm(x) for i in range(len(x))]

def project_onto_plane(x, n):
    d = dot_product(x, n) / norm(n)
    p = [d * normalize(n)[i] for i in range(len(n))]
    return [x[i] - p[i] for i in range(len(x))]

Then you can say:

p = project_onto_plane([3, 4, 5], [1, 2, 3])
Share:
10,344
Sibbs Gambling
Author by

Sibbs Gambling

Updated on July 24, 2022

Comments

  • Sibbs Gambling
    Sibbs Gambling almost 2 years

    I have a plane, plane A, defined by its orthogonal vector, say (a, b, c).

    (i.e. the vector (a, b, c) is orthogonal to plane A)

    I wish to project a vector (d, e, f) onto plane A.

    How can I do it in Python? I think there must be some easy ways.