Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply vector by matrix in R should return vector

Tags:

r

vector

matrix

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

like image 626
CodeGuy Avatar asked May 06 '26 01:05

CodeGuy


2 Answers

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> 
like image 95
Dirk Eddelbuettel Avatar answered May 09 '26 05:05

Dirk Eddelbuettel


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.

like image 30
Jilber Urbina Avatar answered May 09 '26 06:05

Jilber Urbina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!