VLVisual Learner

Vector Subtraction

Time: O(n²)Space: O(1)Stable
Ad

How It Works

Subtracting one vector from another is the same as adding its opposite: a − b = a + (−b). The vector −b has the same length as b but points the other way.

In components, you subtract matching entries: (a₁ − b₁, a₂ − b₂, …, aₙ − bₙ). Both vectors must have the same number of components.

Implementation

// a - b, component by component
function vectorSubtract(a, b) {
  if (a.length !== b.length) {
    throw new Error("Vectors must have the same dimension");
  }
  return a.map((ai, i) => ai - b[i]);
}

// Example: (5, 3) - (2, 4) = (3, -1)
console.log(vectorSubtract([5, 3], [2, 4]));

Deeper Look

Place a and b tail to tail. The difference a − b is the arrow that runs from the tip of b to the tip of a — so b + (a − b) = a. Unlike addition, subtraction is not commutative: b − a points the opposite way to a − b, with the same length.

Displacement

If a and b are position vectors of two points, a − b is the displacement from point B to point A, and its length |a − b| is the distance between them.

Relative Velocity

Physics uses subtraction for relative motion: the velocity of A as seen from B is vA − vB.

Ad