R: matrix by vector multiplication
The %*%
operator in R does matrix multiplication:
> mymat %*% myvec
[,1]
[1,] 116
[2,] 122
...
[10,] 170
Matrix and vector multiplication operation in R
See ?`%*%`
:
Description:
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 of the
same length, it will return the inner product (as a matrix).
Multiply rows of matrix by vector?
I think you're looking for sweep()
.
# Create example data and vector
mat <- matrix(rep(1:3,each=5),nrow=3,ncol=5,byrow=TRUE)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 1 1 1
[2,] 2 2 2 2 2
[3,] 3 3 3 3 3
vec <- 1:5
# Use sweep to apply the vector with the multiply (`*`) function
# across columns (See ?apply for an explanation of MARGIN)
sweep(mat, MARGIN=2, vec, `*`)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 2 4 6 8 10
[3,] 3 6 9 12 15
It's been one of R's core functions, though improvements have been made on it over the years.
R: multiply vector by matrix according to names
You can use subsetting to create a prices vector in the correct order:
pricesm <- prices[rownames(M)]
pricesm
#banana mango pomegranate apple
# 0.42 1.24 2.25 0.85
rev <- pricesm %*% M
rev
# M Tu W Th F
#[1,] 310.44 170.93 243.72 189.85 315.22
Looping over a matrix - vector multiplication, with elements of both changing with each round
a <- matrix(1:36, nrow = 6, byrow = TRUE)
b <- matrix(rep(1, times = 36), nrow = 6, byrow = TRUE)
b1 <- b
b1[1:3,1:3] <- 0
b2 <- b
b2[4:6,4:6] <- 0
my loop codes...
for (i in seq(6)){
temp = rep(0, 6)
temp[i] = 1
assign(paste('c', i, sep = ''), temp)
}
for (i in seq(6)){
cx = get(paste('c', i, sep = ''))
if(i<4){
px = sum(colSums(b1 * diag(as.vector(a %*% cx), nrow = 6)))
assign(paste('d', i, sep = ''), px)
} else{
px = sum(colSums(b2 * diag(as.vector(a %*% cx), nrow = 6)))
assign(paste('d', i, sep = ''), px)
}
}
then the results
results <- cbind(d1, d2, d3, d4, d5, d6)
Nice way to multiply each row of a matrix by a vector in r
I think this is what you are looking for...
t( t(mat) * vec )
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 1 2 3 4
*
like most other operators in R is vectorised. The t
is necessary because R will recycle column-wise. The apply
solution is:
t( apply( mat , 1 , `*` , vec ) )
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 1 2 3 4
Fastest way to multiply matrix columns with vector elements in R
Use some linear algebra and perform matrix multiplication, which is quite fast in R
.
eg
m %*% diag(v)
some benchmarking
m = matrix(rnorm(1200000), ncol=6)
v=c(1.5, 3.5, 4.5, 5.5, 6.5, 7.5)
library(microbenchmark)
microbenchmark(m %*% diag(v), t(t(m) * v))
## Unit: milliseconds
## expr min lq median uq max neval
## m %*% diag(v) 16.57174 16.78104 16.86427 23.13121 109.9006 100
## t(t(m) * v) 26.21470 26.59049 32.40829 35.38097 122.9351 100
Multiply elements of a matrix with vector values
First you need to coerce coords
to a matrix for indexing, then reverse the column order. Then it's just a simple lapply()
loop.
coords <- as.matrix(coords)[, 2:1]
lapply(multis, function(x) {
M[coords] <- M[coords] * x
M
})
resulting in
[[1]]
[,1] [,2] [,3] [,4] [,5]
[1,] 0.1 5 9 13.0 17.0
[2,] 2.0 6 10 1.4 18.0
[3,] 3.0 7 11 15.0 1.9
[4,] 4.0 8 12 16.0 20.0
[[2]]
[,1] [,2] [,3] [,4] [,5]
[1,] 2 5 9 13 17
[2,] 2 6 10 28 18
[3,] 3 7 11 15 38
[4,] 4 8 12 16 20
[[3]]
[,1] [,2] [,3] [,4] [,5]
[1,] 100 5 9 13 17
[2,] 2 6 10 1400 18
[3,] 3 7 11 15 1900
[4,] 4 8 12 16 20
Fastest way for multiplying a matrix to a vector
sweep
seems to run a bit faster on my machine
sweep(mat, 2, v, FUN = "*")
Some benchmarks:
> microbenchmark(mat %*% diag(v),sweep(mat, 2, v, FUN = "*"))
Unit: milliseconds
expr min lq median uq max neval
%*% 214.66700 226.95551 231.2366 255.78493 349.1911 100
sweep 42.42987 44.72254 62.9990 70.87403 127.2869 100
Related Topics
R Ggplot Ordering Bars in "Barplot-Like " Plot
Addsma Not Drawn on Graph When Called from Function
How to Color Entire Background in Ggplot2 When Using Coord_Fixed
Tricks to Override Plot.Factor
Purrr:Map and Glm - Issues with Call
R Converting from Datetime to Date
Does White Space Slow Down Processing
Hyperlink Bar Chart in Highcharter
Rmarkdown in Shiny Application
How to Remove Columns from a Data.Frame by Data Type
Plot with Ggplot in For-Loop Doesn't Work
Rolling Join Grouped by a Second Variable in Data.Table
What Does < Stand for in Data.Table Joins with On=