Multiplication of Vector Combinations

Ordinary vector multiplication of R, only multiplies vectors once or processes a 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 multiply each combination of two vectors. In this particular case, I calculate the maximum speed in MPH that an electric bicycle engine can rotate: *

 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 

I want for mph to contain every combination of the maximum speed of the given wheel diameters with the given maximum speed of the engine.

* Please note that at this speed zero torque will be generated due to reverse emf.

+4
source share
2 answers

You are probably looking for outer() or the binary operator alias %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 to apply to combinations; %o% only the multiplication function * is applied. 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 
+8
source

I believe the function you are 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 can clear the notation a bit:

 outer(cir, rpm / 63360 * 60) 
+5
source

Source: https://habr.com/ru/post/1497119/


All Articles