Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Outer division (vectors to matrix) #2 #1

Open
wageningen opened this issue Nov 18, 2016 · 2 comments
Open

Outer division (vectors to matrix) #2 #1

wageningen opened this issue Nov 18, 2016 · 2 comments

Comments

@wageningen
Copy link
Collaborator

In the R user meeting of Nov 16th, we had a question why

 (1:5) %*% t(2:6)
     [,1] [,2] [,3] [,4] [,5]
[1,]    2    3    4    5    6
[2,]    4    6    8   10   12
[3,]    6    9   12   15   18
[4,]    8   12   16   20   24
[5,]   10   15   20   25   30

but

(1:5) %/% t(2:6)
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0

??
I don't know, but the solution (given by another participant) is:

outer((1:5),(2:6),"/")
     [,1]      [,2] [,3] [,4]      [,5]
[1,]  0.5 0.3333333 0.25  0.2 0.1666667
[2,]  1.0 0.6666667 0.50  0.4 0.3333333
[3,]  1.5 1.0000000 0.75  0.6 0.5000000
[4,]  2.0 1.3333333 1.00  0.8 0.6666667
[5,]  2.5 1.6666667 1.25  1.0 0.8333333
@bbrede
Copy link
Contributor

bbrede commented Nov 23, 2016

Regarding the % operators: They signal a special binary operator. %/% means integer division, %% modulo.
In your example: (1:5) %/% t(2:6) the integer division will be applied and the t() will make the output a matrix, because the second argument is treated as a column vector.

That %*% means matrix multiplication, but %/% integer division is a bit unfortunate in R. But R is not a mathematical language (like Matlab), matrix multiplication is seen as special so get's a special syntax.

BTW: you can define a special binary operator yourself:
%s% <- function(x,y) x + y
3 %s% 4

@almeidaxan
Copy link

Just out of curiosity, the same result can also be achieved without the "outer" function, by simply doing

(1:5) %*% t(1/(2:6))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants