Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiply every member of a R list (matrices) by each other

Tags:

r

I have a list of equally sized matrices in R that I want to multiply by each other.

I am looking for a way to do:

list$A * list$B * list$C * ...

Without having to type it out by hand (my list has dozens of matrices).

like image 761
Ian Fiddes Avatar asked May 28 '14 22:05

Ian Fiddes


People also ask

How do I multiply all values in a list in R?

To multiply all values in a list by a number, we can use lapply function. Inside the lapply function we would need to supply multiplication sign that is * with the list name and the number by which we want to multiple all the list values.

How do you multiply matrices in R programming?

To multiply two matrices by elements in R, we would need to use one of the matrices as vector. For example, if we have two matrices defined by names M1 and M2 then the multiplication of these matrices by elements can be done by using M1*as. vector(M2).

How do you multiply values in R?

In R the asterisk (*) is used for element-wise multiplication. This is where the elements in the same row are multiplied by one another. We can see that the output of c*x and x*c are the same, and the vector x doubles matrix c. In R percent signs combined with asterisks are used for matrix multiplication (%*%).


1 Answers

Use Reduce if you want an element-by-element multiplication

> Lists <- list(matrix(1:4, 2), matrix(5:8, 2), matrix(10:13, 2))
> Reduce("*", Lists)
     [,1] [,2]
[1,]   50  252
[2,]  132  416

Instead of using abind you can use simplify2array function and apply

> apply(simplify2array(Lists), c(1,2), prod)
     [,1] [,2]
[1,]   50  252
[2,]  132  416

If you want to use abind then use the following:

> library(abind)
> apply(abind(Lists, along=3), c(1,2), prod)
     [,1] [,2]
[1,]   50  252
[2,]  132  416
like image 148
Jilber Urbina Avatar answered Nov 15 '22 13:11

Jilber Urbina