Question

I teach mathematics and programming (with R) at university and I am a big fan of a good and consistent notation. Please have a look at the following simple vector operations in R:

> v1 <- c(1,2,3)
> v2 <- c(4,5,6)
> v1 %*% v2
     [,1]
[1,]   32
> t(v1) %*% v2
     [,1]
[1,]   32
> v1 %*% t(v2)
     [,1] [,2] [,3]
[1,]    4    5    6
[2,]    8   10   12
[3,]   12   15   18
> t(v1) %*% t(v2)
Error in t(v1) %*% t(v2) : non-conformable arguments
> v1 + v2
[1] 5 7 9
> v1 + t(v2)
     [,1] [,2] [,3]
[1,]    5    7    9
> t(v1) + t(v2)
     [,1] [,2] [,3]
[1,]    5    7    9

I think there are some inconsistencies here: Either I am missing something or R seems to be quite arbitrary with respect to what results you get when you either transpose a vector or not.

What is the underlying logic here (which seems to be completely different than Matlab by the way).

Was it helpful?

Solution

?%*% gives the logic:

Multiplies two matrices, if they are conformable. If one argument is a vector, it will be promoted to either a row or column matrix to make the two arguments conformable. If both are vectors it will return the inner product (as a matrix).

If they're both vectors (first example), then you get the inner product. If you put a t( ) in there, the vector will get cast as a column matrix, and a vector is effectively a row matrix, so normable conformable rules apply.

Similarly, the help page for "+" says that it will cast the arguments to vectors - and gives some guidance on the 'shape' of the result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top