Karsten W.
Karsten W.

Reputation: 18500

Elementwise Product of Matrix and Vector

Instead of the usual matrix multiplication, I need an elementwise operation. The following works fine:

# this works
Bmat <- structure(c(3L, 3L, 10L, 3L, 4L, 10L, 5L, 8L, 8L, 8L, 3L, 8L, 8L, 2L, 6L, 10L, 2L, 8L, 3L, 9L), .Dim = c(10L, 2L))
yvec <- c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
Bmat * yvec
#       [,1] [,2]
#  [1,]    6    6
#  [2,]    6   16
#  [3,]   20   16
#  [4,]    6    4
#  [5,]    8   12
#  [6,]   20   20
#  [7,]   10    4
#  [8,]   16   16
#  [9,]   16    6
# [10,]   16   18

however, the following fails:

# this fails
Amat <- structure(c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(10L, 2L))
xvec <- structure(c(1.83475682418716, 1.48154883122634, 1, 1, 1, 1, 1, 1, 1, 1), .Dim = c(10L, 1L))
Amat * xvec
#Fehler in Amat * xvec : nicht passende Arrays

Why is that? Has it something to do with the Bmat being an integer matrix? How can I make the second code work?

Upvotes: 3

Views: 457

Answers (1)

d.b
d.b

Reputation: 32548

class(xvec)
[1] "matrix"

dim(xvec)
[1] 10  1

class(Amat)
[1] "matrix"    

dim(Amat)
[1] 10  2

Element wise multiplication between two matrices is only possible when they have same dimension. So, the solution is to convert xvec into a vector. Try

Amat * c(xvec)
#OR
Amat * as.vector(xvec)

Upvotes: 2

Related Questions