[R] multiplying a matrix by a vector
Rui Barradas
ruipbarradas at sapo.pt
Thu Nov 3 22:32:39 CET 2016
Hello,
Take advantage that in R '*' recycles its arguments (the shorter one)
and that the operation is performed column-wise:
t(y * t(x))
Hope this helps,
Rui Barradas
Em 03-11-2016 21:05, Dimitri Liakhovitski escreveu:
> Hello!
>
> I have a matrix x and a vector y:
>
> x <- matrix(1:6, ncol = 2)
> y <- c(2,3)
>
> I need to multiply the first column of x by 2 (y[1]) and the second
> column of x by 3 (y[2]).
>
> Of course, I could do this - but it's column by column:
>
> x[,1] <- x[,1] * y[1]
> x[,2] <- x[,2] * y[2]
> x
>
> Or I could repeat each element of y and multiply two matrices - that's better:
>
> rep.row<-function(x,n){
> matrix(rep(x,each=n),nrow=n)
> }
> y <- rep.row(y, nrow(x))
> x * y
>
> However, maybe there is a more elegant r-like way of doing it?
> Thank you!
>
More information about the R-help
mailing list