Element element of matrix and vector

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

# 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:

# 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? Does it have to do with what Bmat

is an integer matrix? How do I get the second code to work?

+3


source to share


1 answer


class(xvec)
[1] "matrix"

dim(xvec)
[1] 10  1

class(Amat)
[1] "matrix"    

dim(Amat)
[1] 10  2

      

Elemental multiplication between two matrices is possible only when they have the same dimension. So the solution is to convert xvec

to a vector. Try



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

      

+2


source







All Articles