Tou Mou
Tou Mou

Reputation: 1274

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:

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 :

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

Upvotes: 2

Views: 45

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101247

Another base R option using 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

Upvotes: 1

akrun
akrun

Reputation: 887048

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 matrix

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

Upvotes: 3

Related Questions