In R, I want to multiply a 1x3 vector by a 3x3 matrix to produce a 1x3 vector. However R returns a matrix:
> v = c(1,1,0)
> m = matrix(c(1,2,1,3,1,1,2,2,1),nrow=3,ncol=3,byrow=T)
> v*m
[,1] [,2] [,3]
[1,] 1 2 1
[2,] 3 1 1
[3,] 0 0 0
The correct output should be a vector, not a matrix
If in doubt, try the help system, here eg help("*") or help("Arithmetic"). You simply used the wrong operator.
R> v <- c(1,1,0)
R> m <- matrix(c(1,2,1,3,1,1,2,2,1),nrow=3,ncol=3,byrow=T)
R> dim(m)
[1] 3 3
R> dim(v)
NULL
R> dim(as.vector(v))
NULL
R> dim(as.matrix(v, ncol=1))
[1] 3 1
R>
R> m %*% as.matrix(v, ncol=1)
[,1]
[1,] 3
[2,] 4
[3,] 4
R>
Note that we have to turn v into a proper vector first. You did not say whether it was 1x3 or 3x1. But luckily R is generous:
R> v %*% m
[,1] [,2] [,3]
[1,] 4 3 2
R> m %*% v
[,1]
[1,] 3
[2,] 4
[3,] 4
R>
Useful functions in this case are crossprod and tcrossprod
> tcrossprod(v, m)
[,1] [,2] [,3]
[1,] 3 4 4
See ?crossprod and ?tcrossprod for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With