Lesson 4 of 18

Scalar Projection

Scalar Projection

The scalar projection of a\mathbf{a} onto b\mathbf{b} answers: "how much of a\mathbf{a} points in the direction of b\mathbf{b}?"

compb(a)=abb\text{comp}_{\mathbf{b}}(\mathbf{a}) = \frac{\mathbf{a} \cdot \mathbf{b}}{|\mathbf{b}|}

This is the signed length of the shadow of a\mathbf{a} onto the line through b\mathbf{b}.

Derivation

From the dot product formula: ab=abcos(θ)\mathbf{a} \cdot \mathbf{b} = |\mathbf{a}| \cdot |\mathbf{b}| \cdot \cos(\theta)

Dividing by b|\mathbf{b}|:

compb(a)=acos(θ)=abb\text{comp}_{\mathbf{b}}(\mathbf{a}) = |\mathbf{a}| \cos(\theta) = \frac{\mathbf{a} \cdot \mathbf{b}}{|\mathbf{b}|}

Vector Projection

The vector projection (not required here) returns the actual vector:

projb(a)=abb2b\text{proj}_{\mathbf{b}}(\mathbf{a}) = \frac{\mathbf{a} \cdot \mathbf{b}}{|\mathbf{b}|^2} \cdot \mathbf{b}

Examples

a\mathbf{a}b\mathbf{b}compb(a)\text{comp}_{\mathbf{b}}(\mathbf{a})
(3,4,0)(1,0,0)3 (just the x-component)
(1,1,1)(0,1,0)1 (just the y-component)
(3,4,0)(3,4,0)$5 =

Your Task

Implement double scalar_proj(double ax, double ay, double az, double bx, double by, double bz) that returns the scalar projection of a\mathbf{a} onto b\mathbf{b}.

Use #include <math.h> for sqrt.

TCC compiler loading...
Loading...
Click "Run" to execute your code.