Multiply matrices in list

江枫思渺然 提交于 2019-12-01 07:28:29

问题


I would like to multiply multiple matrices of a list. I know that this works with a single matrix:

 x1  <- c(2,2,2,3,1,2,4,6,1,2,4)
 y1  <- c(5,4,3,3,4,2,1,6,4,2,3)
 x2  <- c(8,2,7,3,1,2,2,2,1,2,6)
 y2  <- c(1,3,3,3,1,2,4,3,1,2,8)
 x3  <- c(1,0,1,0,0,0,1,1,1,1,1)
 y3  <- c(1,0,0,0,0,0,1,1,0,1,0)
 x4  <- c(1,0,1,0,0,0,0,1,0,1,0)
 y4  <- c(1,0,1,0,0,0,1,1,1,1,1)

 mat1 <- cbind(x1,y1,x2,y2); mat1
 mat2 <- cbind(x3,y3,x4,y4); mat2

 mat3 <- mat1*mat2; mat3

The result is as I wished, when the second matrix had a zero, then the value was set to zero in the result, otherwise the result was kept the same:

       x1 y1 x2 y2
 [1,]  2  5  8  1
 [2,]  0  0  0  0
 [3,]  2  0  7  3
 [4,]  0  0  0  0
 [5,]  0  0  0  0
 [6,]  0  0  0  0
 [7,]  4  1  0  4
 [8,]  6  6  2  3
 [9,]  1  0  0  1
[10,]  2  2  2  2
[11,]  4  0  0  8

Now, consider a list with multiple matrices, both lists have the same matrices, one the values, the other one containing 1/0 but in the exact same size. How can I reach the same result as above, e.g., multiplying both first matrices, then both second matrices and so on. the result as above would be for the pair of first matrices.


回答1:


So generically, how do you multiply corresponding members of two lists? Suppose the matrices with values are in list1 and those with 0/1 are in list2, then one way to do it is with lapply

 answer <- lapply(seq_along(list1),FUN=function(i) list1[[i]]*list2[[i]])

Your resulting matrices will be the elements of answer.




回答2:


Map is your friend for these sorts of operations. First, let's make some example lists using your data:

l1 <- replicate(3,mat1,simplify=FALSE)
l2 <- replicate(3,mat2,simplify=FALSE)

Now, it's as simple as:

Map("*",l1,l2)


来源:https://stackoverflow.com/questions/25233916/multiply-matrices-in-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!