Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying vector combinations

Tags:

r

Normal R vector multiplication, only multiplies vectors once, or recycles the shorter vector. IE:

> c(2,3,4) * c(1,2)
[1] 2 6 4
Warning message:
In c(2, 3, 4) * c(1, 2) :
  longer object length is not a multiple of shorter object length

What I would like to do is to multiply every combination of two vectors. In this specific case, I'm calculating the maximum speed in MPH that an electric bicycle motor can spin:*

d <- c(20,26,29) #bicycle wheel diameter possibilities in inches
rpm <- c(150,350) #maximum motor RPM. Choices depends on motor winding.
cir <- pi * d #circumference
mph <- cir * rpm / 63360 * 60 #max speed in mph for each wheel diameter and RPM combination
mph

What I would like is for mph to contain every maximum speed combination of the given wheel diameters with the given max motor RPM.

* Please note that it will be generating zero torque at this speed because of back EMF.

like image 837
variable Avatar asked Aug 14 '13 20:08

variable


People also ask

What happens when you multiply vectors together?

When two vectors are multiplied with each other and the multiplication is also a vector quantity, then the resultant vector is called the cross product of two vectors or the vector product. The resultant vector is perpendicular to the plane containing the two given vectors.

How do you find the combination between two vectors?

The number of possible combinations of two vectors can be computed by multiplying all the successive elements of the first vector with the corresponding elements of the second vector.


2 Answers

You are probably looking for outer() or it's alias binary operator %o%:

> c(2,3,4) %o% c(1,2)
     [,1] [,2]
[1,]    2    4
[2,]    3    6
[3,]    4    8
> outer(c(2,3,4), c(1,2))
     [,1] [,2]
[1,]    2    4
[2,]    3    6
[3,]    4    8

In your case, outer() offers the flexibility to specify a function that is applied to the combinations; %o% only applies the * multiplication function. For your example and data

mph <- function(d, rpm) {
    cir <- pi * d
    cir * rpm / 63360 * 60
}

> outer(c(20,26,29), c(150,350), FUN = mph)
          [,1]     [,2]
[1,]  8.924979 20.82495
[2,] 11.602473 27.07244
[3,] 12.941220 30.19618
like image 189
Gavin Simpson Avatar answered Oct 21 '22 05:10

Gavin Simpson


I believe the function you're looking for is outer

> outer(cir, rpm, function(X, Y) X * Y / 63360 * 60)
          [,1]     [,2]
[1,]  8.924979 20.82495
[2,] 11.602473 27.07244
[3,] 12.941220 30.19618

In this case you could clean up the notation a bit:

outer(cir, rpm / 63360 * 60)
like image 5
Señor O Avatar answered Oct 21 '22 06:10

Señor O