简体   繁体   English

如何将矩阵与多个向量相乘以获得矩阵列表?

[英]How to multiply a matrix with more than one vector to obtain a list of matrices?

Assume we have the following matrix:假设我们有以下矩阵:

m=matrix(1:6,ncol=2)

     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

Using sweep we can multiply the matrix m with some vector v :使用sweep ,我们可以将矩阵m与某个向量v相乘:

v=c(3,4)

sweep(m , MARGIN=2, v , `*`)

# Output :
         [,1] [,2]
    [1,]    3   16
    [2,]    6   20
    [3,]    9   24

I am searching to do this with more than one vector.我正在寻找不止一个向量来做到这一点。 For example:例如:

v_matrix=matrix(data=c(3,4,7,8),ncol=2,byrow=TRUE)

v_matrix

     [,1] [,2]
[1,]    3    4
[2,]    7    8

The expected output is:预期的 output 为:

[[1]]
     [,1] [,2]
[1,]    3   16
[2,]    6   20
[3,]    9   24
[[2]]
     [,1] [,2]
[1,]    7   32
[2,]   14   40
[3,]   21   48

Loop over the v_matrix by row in apply , and then use the sweep on the row values which is a vector with 'm' as matrixapply中逐行循环遍历v_matrix ,然后对行值进行sweep ,这是一个以 'm' 作为matrixvector

do.call("c", apply(v_matrix, 1, function(x) list(sweep(m, MARGIN = 2, x, `*`))))

-output -输出

#[[1]]
#     [,1] [,2]
#[1,]    3   16
#[2,]    6   20
#[3,]    9   24

#[[2]]
#     [,1] [,2]
#[1,]    7   32
#[2,]   14   40
#[3,]   21   48

Another base R option using Map另一个基础 R 选项使用Map

> Map(function(x, y) t(x * y), list(t(m)), data.frame(t(v_matrix)))
[[1]]
     [,1] [,2]
[1,]    3   16
[2,]    6   20
[3,]    9   24

[[2]]
     [,1] [,2]
[1,]    7   32
[2,]   14   40
[3,]   21   48

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM