Home > Software design >  Multiplying a 5X3 matrix and 3X1 vector in R
Multiplying a 5X3 matrix and 3X1 vector in R

Time:04-04

I am starting to learn R and trying to multiply a 5X3 matrix with a 3X1 column vector in R; However while creating a new variable to perform the operation, R throws the error "non-conformable arrays". Can someone please point out my mistake in the code below -

*#5X3 Matrix*
X  <- matrix(c(1,25.5,1.23,1,40.8,1.89,1,30.2,1.55,1,4.3,1.18,1,10.7,1.68),nrow=5,ncol=3,byrow=TRUE)
*3X1 Column vector*
b1 <- matrix(c(23,0.1,-8), nrow = 3, ncol = 1, byrow = TRUE)
v1 <- X * b1
v1

Appreciate your help :)

CodePudding user response:

You need the matrix-multiplication operator %*%:

X  <- matrix(c(1,25.5,1.23,1,40.8,1.89,1,30.2,1.55,1,4.3,1.18,1,10.7,1.68),nrow=5,ncol=3,byrow=TRUE)
b1 <- matrix(c(23,0.1,-8), nrow = 3, ncol = 1, byrow = TRUE)
v1 <- X %*% b1
v1
#>       [,1]
#> [1,] 15.71
#> [2,] 11.96
#> [3,] 13.62
#> [4,] 13.99
#> [5,] 10.63

CodePudding user response:

Normally one would use the first alternative below but the others are possible too. The first four alternatives below give a column vector as the result while the others give a plain vector without dimensions. The first three work even if b1 has more than one column. The remainder assume b1 has one column but could be generalized.

X %*% b1

crossprod(t(X), b1)

library(einsum)
einsum("ij,jk -> ik", X, b1)

out <- matrix(0, nrow(X), ncol(b1))
for(i in 1:nrow(X)) {
  for(k in 1:ncol(X)) out[i] <- out[i]   X[i, k] *  b1[k, 1]
}
out

colSums(t(X) * c(b1))

apply(X, 1, crossprod, b1)

sapply(1:nrow(X), function(i) sum(X[i, ] * b1))

rowSums(mapply(`*`, as.data.frame(X), b1))

rowSums(sapply(1:ncol(X), function(j) X[, j] * b1[j]))

X[, 1] * b1[1, 1]   X[, 2] * b1[2, 1]   X[, 3] * b1[3, 1]

Note

The input shown in the question is:

X  <- matrix(c(1,25.5,1.23,1,40.8,1.89,1,30.2,1.55,1,4.3,1.18,1,10.7,1.68),nrow=5,ncol=3,byrow=TRUE)
b1 <- matrix(c(23,0.1,-8), nrow = 3, ncol = 1, byrow = TRUE)
  •  Tags:  
  • r
  • Related