If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Main content

More vector math

Addition was really just the first step. There are many mathematical operations that are commonly used with vectors. Below is a comprehensive list of the operations available as functions in the PVector object from ProcessingJS. We’ll go through a few of the key ones now. As our examples get more sophisticated in later sections, we’ll continue to reveal the details of more functions.
  • add() — add vectors
  • sub() — subtract vectors
  • mult() — scale the vector with multiplication
  • div() — scale the vector with division
  • mag() — calculate the magnitude of a vector
  • normalize() — normalize the vector to a unit length of 1
  • limit() — limit the magnitude of a vector
  • heading2D() — the 2D heading of a vector expressed as an angle
  • dist() — the Euclidean distance between two vectors (considered as points)
  • angleBetween() — find the angle between two vectors
  • dot() — the dot product of two vectors
  • cross() — the cross product of two vectors (only relevant in three dimensions)
Having already covered addition, let’s start with subtraction. This one’s not so bad; just take the plus sign and replace it with a minus!

Vector Subtraction

w=uv
can be written as:
wx=uxvx
wy=uyvy
and so the function inside PVector looks like:
PVector.prototype.sub = function(vector2) {
    this.x = this.x - vector2.x;
    this.y = this.y - vector2.y;
  };
The following example demonstrates vector subtraction by taking the difference between two points (the mouse location and the center of the window).
Basic Number Properties with Vectors
When we're doing math with real numbers, they obey these basic rules:
The commutative rule: 3+2=2+3
The associative rule: (3+2)+1=3+(2+1)
Those same rules are true of math with vectors:
The commutative rule: u+v=v+u
The associative rule: u+(v+w)=(u+v)+w

Vector Multiplication

Moving on to multiplication, we have to think a little bit differently. When we talk about multiplying a vector, what we typically mean is scaling a vector. If we wanted to scale a vector to twice its size or one-third of its size (leaving its direction the same), we would say: “Multiply the vector by 2” or “Multiply the vector by 1/3.” Note that we are multiplying a vector by a scalar, a single number, not another vector.
To scale a vector, we multiply each component (x and y) by a scalar.
w=un
can be written as:
wx=uxnwy=uyn
Scaling a vector
Let’s look at an example with vector notation.
u=(3,7)n=3w=unwx=33wy=73w=(9,21)
Therefore, the function inside the PVector object is written as:
PVector.prototype.mult = function(n) {
   this.x = this.x * n;
   this.y = this.y * n;
}
And using mult in code is as simple as:
var u = new PVector(-3,7);
// This PVector is now three times the size and is equal to (-9,21).
u.mult(3);
Here's the example from earlier, but we multiply the vector by 0.5 each time, so that it's scaled by half:
Instead of multiplying by 0.5 above, we could have also divided by 2. Division works just like multiplication—we simply replace the multiplication sign (asterisk) with the division sign (forward slash).
This is how the div method is implemented internally:
PVector.prototype.div = function(n) {
   this.x = this.x / n;
   this.y = this.y / n;
}
And this is how we can use it in code:
var u = new PVector(8, -4);
u.div(2);

More Number Properties with Vectors

As with addition, basic algebraic rules of multiplication apply to vectors.
The associative rule: (nm)v=n(mv)
The distributive rule with 2 scalars, 1 vector: (n+m)v=nv+mv
The distributive rule with 2 vectors, 1 scalar: (u+v)n=un+vn
Want to practice your vector math? You can learn more here on Khan Academy, in our Linear Algebra: Vectors unit.

This "Natural Simulations" course is a derivative of "The Nature of Code" by Daniel Shiffman, used under a Creative Commons Attribution-NonCommercial 3.0 Unported License.

Want to join the conversation?

  • blobby green style avatar for user Jiri
    In the last paragraph there is probably a mistake.
    The distributive rule with 2 scalars, 1 vector: (n∗m)∗v⃗ =n∗v⃗ +m∗v⃗
    Between n and m should be a plus sign instead of a multiplication sign. So:
    The distributive rule with 2 scalars, 1 vector: (n+m)∗v⃗ =n∗v⃗ +m∗v⃗
    (58 votes)
    Default Khan Academy avatar avatar for user
  • primosaur ultimate style avatar for user Sean
    in the first example couldn't you just do this

    var draw = function() {

    background(255, 255, 255);
    stroke(255, 0, 0);
    strokeWeight(3);
    line(200, 200, mouseX, mouseY);
    };
    (16 votes)
    Default Khan Academy avatar avatar for user
    • starky ultimate style avatar for user Jim Durand
      Yes, that would work, but it uses techniques that you already knew before learning about vectors. The point of the example is to illustrate subtraction of vectors. The subtraction occurs when the center of the canvas (vector center) is subtracted from the mouse position (vector mouse). Vector mouse represents the mouse position, but it's now relative to the center of the canvas (meaning position (0,0) is the canvas center).
      If the coordinate system used for storing a mouse position is changed to make (0,0) the center of the canvas, the way it's drawn must also be changed. This was done in the example by using translate so that the drawing coordinate system is also at the center of the canvas.
      (20 votes)
  • hopper cool style avatar for user DVRazor
    Operations over vectors like .add(), sub(), mult() etc. change the vectors themselves. What if I wanted to introduce a new variable, a new PVector and assign it to for example a sum of two other vectors, but not change them?
    Like newVector = a + b
    (5 votes)
    Default Khan Academy avatar avatar for user
  • aqualine seed style avatar for user William Hooton
    Can someone pleas help me on the next challenge i don't get it
    (4 votes)
    Default Khan Academy avatar avatar for user
    • leaf green style avatar for user Anas
      var v = new PVector(50, 75);

      var drawSaber = function() {
      background(0, 0, 0);
      // glow
      strokeWeight(8);
      stroke(107, 206, 219, 150);
      line(0, 400, v.x, 400-v.y);
      // blade
      stroke(255, 255, 255);
      strokeWeight(4);var v = new PVector(50, 75);

      var drawSaber = function() {
      background(0, 0, 0);
      // glow
      strokeWeight(8);
      stroke(107, 206, 219, 150);
      line(0, 400, v.x, 400-v.y);
      // blade
      stroke(255, 255, 255);
      strokeWeight(4);
      line(0, 400, v.x, 400-v.y);
      };

      keyPressed = function(){
      if (keyCode === UP){
      v.mult(2);
      } else if(keyCode === DOWN){
      if (keyCode === DOWN){
      v.div(2);
      }
      }
      drawSaber();
      };

      line(0, 400, v.x, 400-v.y);
      };

      drawSaber();
      (4 votes)
  • leaf green style avatar for user Braden Green
    I don't understand what resetMatrix() does, can anybody explain it to me?
    (4 votes)
    Default Khan Academy avatar avatar for user
    • hopper jumping style avatar for user SapFire13
      Let's think of it this way.
      You have a program consisting of a tree and a snowflake; and you want to rotate the snowflake by 20 degrees.
      You could put the rotate(20) line in front of the code, but that would rotate both the snowflake and the tree, because the draw function repeats itself for the program lifetime. On the other hand, if you omit the function, you don't have animation.
      ----------------------------------------------------------------------------------------------------------------------
      There's a solution!
      You just "enclose" the snowflake drawing code and its rotate function in a chunk of code.
      The first line is:
      pushMatrix();
      That "activates" the matrix, anything after will be affected by transformations.
      rotate(20);
      Then you have the snowflake drawing code (here).
      And then:
      popMatrix();
      That line "disactivates" the matrix. Anything after or before that chunk of code (from the "push" to the "pop" will not be rotated).
      -----------------------------------------------------------------------------------------------------------------------
      But let's assume that you have a really big program and you want to save code.
      You would write the above code this way:
      rotate(20);
      Aha, the computer got a command to rotate the canvas by 20 degrees.
      Here - the snowflake drawing command.
      resetMatrix();
      This function serves the same purpose as the popMatrix() function -- except that you don't need the "push" anymore. The "reset" function, as it says, resets the canvas to a neutral state.
      Hope that helped,
      - SapFire13
      (5 votes)
  • duskpin ultimate style avatar for user Arki🖤
    What is the difference between dist(); and mag();
    (4 votes)
    Default Khan Academy avatar avatar for user
  • piceratops ultimate style avatar for user Iivis
    In the two example programs, what does " translate (width/2, height/2) " mean? It isn't mentioned in the operator list at the start of the article.
    (2 votes)
    Default Khan Academy avatar avatar for user
    • hopper cool style avatar for user BenR
      Ok, in JS, translate moves an object according to the amount of pixels entered into the arguments. In this case, width/2 and height/2 were used. So, instead of saying translate(200,200); which would only be centered for a 400x400 canvas, translate(width/2,height/2); was used to center it on all canvases.
      (6 votes)
  • hopper cool style avatar for user Daiwei Wang
    could someone help me on the
    LightSaber Challenge
    ? Thanks!
    (3 votes)
    Default Khan Academy avatar avatar for user
  • winston default style avatar for user I want to leave this empty
    why is vector math so important just stick to easy math
    (0 votes)
    Default Khan Academy avatar avatar for user
  • hopper jumping style avatar for user Abigail
    I used v = mult(v); but It says mult is not defined. Is there something I'm missing?
    (2 votes)
    Default Khan Academy avatar avatar for user