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.

### Course: Computer programming - JavaScript and the web>Unit 5

Lesson 4: Vectors

# 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.

### Vector Subtraction

$\stackrel{\to }{w}=\stackrel{\to }{u}-\stackrel{\to }{v}$
can be written as:
${\text{w}}_{x}={\text{u}}_{x}-{\text{v}}_{x}$
${\text{w}}_{y}={\text{u}}_{y}-{\text{v}}_{y}$
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: $\left(3+2\right)+1=3+\left(2+1\right)$
Those same rules are true of math with vectors:
The commutative rule: $\stackrel{\to }{u}+\stackrel{\to }{v}=\stackrel{\to }{v}+\stackrel{\to }{u}$
The associative rule: $\stackrel{\to }{u}+\left(\stackrel{\to }{v}+\stackrel{\to }{w}\right)=\left(\stackrel{\to }{u}+\stackrel{\to }{v}\right)+\stackrel{\to }{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.
$\stackrel{\to }{w}=\stackrel{\to }{u}\ast n$
can be written as:
$\begin{array}{rl}& {w}_{x}={u}_{x}\ast n\\ & {w}_{y}={u}_{y}\ast n\end{array}$
Let’s look at an example with vector notation.
$\begin{array}{rl}& \stackrel{\to }{u}=\left(-3,7\right)\\ & n=3\\ & \stackrel{\to }{w}=\stackrel{\to }{u}\ast n\\ & {w}_{x}=-3\ast 3\\ & {w}_{y}=7\ast 3\\ & \stackrel{\to }{w}=\left(-9,21\right)\end{array}$
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: $\left(n\ast m\right)\ast \stackrel{\to }{v}=n\ast \left(m\ast \stackrel{\to }{v}\right)$
The distributive rule with 2 scalars, 1 vector: $\left(n+m\right)\ast \stackrel{\to }{v}=n\ast \stackrel{\to }{v}+m\ast \stackrel{\to }{v}$
The distributive rule with 2 vectors, 1 scalar: $\left(\stackrel{\to }{u}+\stackrel{\to }{v}\right)\ast n=\stackrel{\to }{u}\ast n+\stackrel{\to }{v}\ast n$

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?

• In the last paragraph there is probably a mistake.
The distributive rule with 2 scalars, 1 vector: (n∗m)∗v⃗ =n∗v⃗ +m∗v⃗
The distributive rule with 2 scalars, 1 vector: (n+m)∗v⃗ =n∗v⃗ +m∗v⃗
• Such problems can be reported using the 'Report a mistake in the article' button at the top-right of the discussion panel, possibly even leading to the 'Fact Checker' moon badge. Someone else already reported this mistake.
• 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);
};
• 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.
• 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
• Can someone pleas help me on the next challenge i don't get it
• 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);
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);
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();
• I don't understand what resetMatrix() does, can anybody explain it to me?
• 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
• What is the difference between dist(); and mag();
• The .mag() method of a PVector finds the magnitude of the vector, which is the distance between the vector and (0, 0, 0). PVector.dist(vector2) finds the distance between the vector and vector2.
• 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.
• 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.
• could someone help me on the
LightSaber Challenge
? Thanks!
• Also, make sure you move the drawSaber function inside the keyPressed function. If you don't, the drawing won't update when you multiple/divide the vector.
• why is vector math so important just stick to easy math
        myVector.mult(scale)
If your vector is called v and you want to scale it up by a factor of 4, you would write
        v.mult(4);