简体   繁体   中英

Multiply vector by matrix in R should return vector

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.

Are you looking for

as.vector(v %*% m)

?

Here the documentation of matmult :

 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM