列表中的矩阵相乘 [英] Multiply matrices in list

查看:70
本文介绍了列表中的矩阵相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个列表的多个矩阵相乘.我知道这适用于单个矩阵:

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

现在,考虑一个包含多个矩阵的列表,两个列表具有相同的矩阵,一个为值,另一个列表包含1/0,但大小完全相同.如何获得与上述相同的结果,例如,将两个第一个矩阵相乘,然后再将两个第二个矩阵相乘,依此类推.上面的结果将是一对第一矩阵的结果.

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.

推荐答案

因此,通常来说,如何将两个列表的对应成员相乘?假设值的矩阵在list1中,而值0/1的矩阵在list2中,则使用lapply的方法之一

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]])

您得到的矩阵将是answer的元素.

Your resulting matrices will be the elements of answer.

这篇关于列表中的矩阵相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆