Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Ruby, Vectors

ruby

  • Please log in to reply
3 replies to this topic

#1 RhetoricalRuvim

RhetoricalRuvim

    JavaScript Programmer

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1311 posts
  • Location:C:\Countries\US
  • Programming Language:C, Java, C++, PHP, Python, JavaScript

Posted 27 August 2011 - 09:57 PM

Let's work with point vectors, this time. First of all, what is a vector? A vector could be a quantity with magnitude and direction; but for some reason, a lot of the times, vectors are represented by points.

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, B) and (c, d), we just need to add the corresponding values; so (a, B) + (c, d) = (a + c, b + d).

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, B) - (c, d) = (a - c, b - d).

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, B) * c = c(a, B) = (a * c, b * c)

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, B) . (c, d) = (a * c) + (b * d)

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
Posted Image

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

  • 0

#2 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 30 August 2011 - 06:17 AM

Neat, what if you wanted to extend these functions to work for vectors with any number of elements?

Say I have:

a = (x1, x2, x3, ..., xn)
b = (y1, y2, y3, ..., yn)

Then a + b = (x1 + y1, x2 + y2, ..., xn + yn)

How would you modify the add function to do this?

What if you want the add function to be able to add any number of vectors together. How would you do that?

What about cross products?
  • 0

#3 RhetoricalRuvim

RhetoricalRuvim

    JavaScript Programmer

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1311 posts
  • Location:C:\Countries\US
  • Programming Language:C, Java, C++, PHP, Python, JavaScript

Posted 30 August 2011 - 10:23 AM

Sure. I don't know what you meant by "cross products" but the rest of the questions I worked on here:
def add a, b 

	# If different number of elements for a and b then 

	# fail. 

	if a.length != b.length 

		return false 

	end 

	# line [now - 3] checks if the number of elements 

	# in 	`a` is different than the number of elements 

	# in `b` ; 

	# If so, the next line returns from the function, 

	# with a value of false. 

	# The line after that line tells ruby that it's 

	# the end of the 'if' statement. 

	

	# `c` is our answer array; we initialize it to 

	# having only one element of the answer. 

	c= [a[0] + b[0]] 

	

	# Now we need to loop and set all the other 

	# elements of the answer array. 

	for i in 1..(a.length - 1) 

		# Since we don't know the number of 

		# elements to add in the arrays, 

		# when we make this function, 

		# we have to make a loop that 

		# would keep working on values 

		# until it reaches the last element. 

		# Since we already set element 0 for 

		# our answer, we need now to start 

		# with 1. And since a.length - 1 is 

		# the index to the last element in a 

		# (indexes start with 0, not with 1), 

		# we stop after working on that. 

		

		c[i]= a[i] + b[i] 

		# We set element at index `i` of the answer 

		# to the sum of the elements at index `i` 

		# of `a` and `b` ; that's how vectors are 

		# added. 

	end 

	# And we tell ruby that this is the end of 

	# the code for the loop. 

	

	# `c` should now be the array for the answer. 

	# We need to return `c` . 

	c 

end 



def addAny arr 

	# Set c to the first vector in the array. 

	c= arr[0] 

	# Iterate and add all the following vectors to c. 

	for i in 1..(arr.length - 1) 

		c= add c, arr[i] 

	end 

	# Return c (the answer). 

	c 

end 



def vctFromVal val 

	# Get vector using a values string. 

	

	# The .split() method splits the string into multiple strings, 

	# using the specified delimiter (divider), and returns an 

	# array with all the resulting strings. 

	a= val.split "," 

	

	# `c` is a blank array; we'll use it for our answer. 

	c= [] 

	

	# Iterate through the elements in the string array and 

	# prepare the answer array along the way. 

	for i in 0..(a.length - 1) 

		# Similar type of array as before, but this time 

		# we haven't done the first element yet, so we 

		# start from 0 (index to the first element). 

		

		# We'll use `b` as our temporary string variable. 

		b= a[i] 

		

		# Take out all the spaces from the string. 

		b= b.split(" ").join 

		

		# Set the answer at `i` to the string->float of b. 

		c[i]= b.to_f 

	end 

	

	# We return `c` . 

	c 

end 



puts "When you have all the values for all the vectors entered, press return (enter) to calculate the result. " 

puts 



# vectors is the array we have for all the input vectors. 

vectors= [] 

# We'll initialize input to "nothing" (we can't leave it blank or else the 

# while loop would terminate before the user even has a chance to type 

# anything). 

input= "nothing" 

# Now the while loop; when the user just presses return (enter), this value will be blank, 

# so the while loop will exit. 

while input != '' 

	# Ask user for input. 

	puts "Enter the values, seperated by commas (,), for vector #{vectors.length + 1}:" 

	# Get user input. 

	input= gets.chomp 

	

	# If input not blank, ... 

	if input != '' 

		# Append user input vector to our vectors array. 

		vectors[vectors.length]= vctFromVal input 

	end 

end 



# Now it's time to add the vectors in the array. 

w= addAny vectors 



if w 

	# If successful, notify the user of the answer. 

	puts 'The answer is: ' 

	

	print w 

else 

	# Else, tell the user there was an error. 

	puts 'Error:  The two vectors have to have the same number of values. ' 

end

  • 0

#4 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 03 September 2011 - 06:37 AM

You can simplify the add function slightly. Why did you choose to manually calculate c[0] when you can let the loop do this...

def add a, b 
    if a.length != b.length 
        return false 
    end 

    c= [a[0] + b[0]] 
    
    for i in 1..(a.length - 1)   
        c[i]= a[i] + b[i] 
    end 

    c 
end 

Like this:

def add a, b 
    if a.length != b.length 
        return false 
    end 

    c= []
    
    for i in 0..(a.length - 1)   
        c[i]= a[i] + b[i] 
    end 

    c 
end 

Just start the loop at zero instead of 1.


Also you don't know about cross products? The dot product operation gives you a scalar as the result. The cross product which is also known as the vector product gives you a vector as the answer. The vector that is produced when you do a x b (read a cross B) is a vector that is perpendicular to both a and b. In the general case this is a very complicated function to implement. Cross product is calculated using determinants. One method to calculate this is to use a cofactor expansion.

One practical use of this is determining if an object is inside a region.
  • 1





Also tagged with one or more of these keywords: ruby

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download