【发布时间】:2020-12-13 14:04:06
【问题描述】:
我在 Google 上进行了广泛搜索,但似乎无法找到我的问题的答案。抱歉,如果以前有人问过这个问题。我有两个矩阵,a & b,每个都有相同的维度。我要做的是遍历 a 的行(从 i = 1 到 a 中的行数)并检查矩阵 a 的第 i 行中找到的 any 元素是否出现在相应行中矩阵 b。我有一个使用 sapply 的解决方案,但是对于非常大的矩阵,这会变得非常慢。我想知道是否有可能以某种方式对我的解决方案进行矢量化?以下示例:
# create example matrices
a = matrix(
1:9,
nrow = 3
)
b = matrix(
4:12,
nrow = 3
)
# iterate over rows in a....
# returns TRUE for each row of a where any element in ith row is found in the corresponding row i of matrix b
sapply(1:nrow(a), function(x){ any(a[x,] %in% b[x,])})
# however, for large matrices this performs quite poorly. is it possible to vectorise?
a = matrix(
runif(14000000),
nrow = 7000000
)
b = matrix(
runif(14000000),
nrow = 7000000
)
system.time({
sapply(1:nrow(a), function(x){ any(a[x,] %in% b[x,])})
})
【问题讨论】: