矩阵和向量的元素乘积

时间:2017-04-07 16:56:20

标签: r matrix

我需要元素运算,而不是通常的矩阵乘法。以下工作正常:

# 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

然而,以下失败:

# 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

为什么?它与Bmat是一个整数矩阵有关吗?如何使第二个代码有效?

1 个答案:

答案 0 :(得分:2)

class(xvec)
[1] "matrix"

dim(xvec)
[1] 10  1

class(Amat)
[1] "matrix"    

dim(Amat)
[1] 10  2

两个矩阵之间的元素乘法只有在它们具有相同维度时才有可能。因此,解决方案是将xvec转换为向量。试试

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