Overview
- Vectors
- Vector Operations
- Example Program
Vectors
Vectors are supposed to have magnitude and direction; why should they be represented by points? They don't necessarily have to be; there are these things called polar coordinates.
With polar coordinates, there is a radius value and a direction value. So if you have a radius of 5 and a direction of pi/4, the x and y coordinates would be (5cos(pi/4), 5sin(pi/4)).
If you have the point (x, y) and you want to convert that to polar coordinates, that would be radius= radical( (x**2) + (y**2) ) and the direction would be atan(y/x).
There could also be 3D polar coordinates, I think, but they're more complicated and we won't go over those, here.
Even though polar coordinates are nice, we'll use the point type of vectors for this tutorial.
Let's say
x= 0 y= 1
and let's use this type of vector access:
the_vector= [the_x_value, the_y_value]
So when we need to access a vector's X, we do this:
the_vector[x] ... and so on ...
So let's take a look at some vector operations.
Vector Operations
Vector Addition
To add two vectors, (a,


So, let's write the function for adding a and b:
def vector_add a, b [a[x] + b[x], a[y] + b[y]] end
Vector Subtraction
To subtract one vector from another, we need just to subtract the corresponding values; sort of like this: (a,

Okay, now the code:
def vector_sub a, b [a[x] - b[x], a[y] - b[y]] end
Vector Multiplication By Scalar
All we have to do to multiply a vector by a scalar, is multiply each value in the vector by that scalar.
A scalar, by the way, is just a number.
So, (a,


The code:
def vector_mul a, c [a[x] * c, a[y] * c] end
Vector Dot Product
To find the dot product of two vectors, all you have to do is multiply each coordinate of vector 1 by the corresponding coordinate of vector 2 and add all the products together.
(a,

The code:
def vector_dot a, b (a[x] * b[x]) + (a[y] * b[y]) end
So, now the example program.
Example Program
The Code
# Define the x and y indexes. x= 0 y= 1 def ask_vector_01 m, n "Enter the #{m} value for #{n}: " end def ask_vector a puts ask_vector_01 "X", a x= gets.to_f puts ask_vector_01 "Y", a y= gets.to_f [x, y] end # Get the first vector. u= ask_vector "vector 1" # Get the second vector. v= ask_vector "vector 2" # Add the two vectors. w= [u[x] + v[x], u[y] + v[y]] # Tell the user the result. puts "Result of vector addition: (#{w[x]}, #{w[y]})" # Wait for return key press. gets
The Output

(Fullsize Screenshot)
First Tutorial:
Hello World Introduction
Previous Tutorial:
File I/O
Next Tutorial:
If...Else, For, While
Edited by RhetoricalRuvim, 27 August 2011 - 10:36 PM.