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).
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.
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).
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 (%*%).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With