3
我有一个不同大小的矩阵列表。我如何快速总结矩阵列表中的所有元素?在R中加上矩阵列表
这是我目前的代码,但它很慢。有更快的方法吗?
for (i in 1: length(w)) {
w_sum <- w_sum + sum(apply(w[[i]], 1:2, function (x) x^2))
}
我有一个不同大小的矩阵列表。我如何快速总结矩阵列表中的所有元素?在R中加上矩阵列表
这是我目前的代码,但它很慢。有更快的方法吗?
for (i in 1: length(w)) {
w_sum <- w_sum + sum(apply(w[[i]], 1:2, function (x) x^2))
}
矩阵是引擎盖下只是载体,因此你可以unlist
,方形和sum
:
sum(unlist(w)^2)
#[1] 2393
使用@ akrun的示例数据,给出了相同的结果。
这是更快,如果你有矩阵吨:
w <- rep(list(matrix(1:24,nrow=6)), 1e6)
system.time(sum(unlist(w)^2))
# user system elapsed
# 0.11 0.00 0.10
system.time(sum(vapply(w, function(x) sum(x^2), numeric(1))))
# user system elapsed
# 2.17 0.00 2.17
循环也不必在这种情况下慢得离谱对比:
w_sum <- 0
system.time(for(i in seq_along(w)) { w_sum <- w_sum + sum(w[[i]]^2) })
# user system elapsed
# 2.62 0.00 2.62
这是我的结果,我错过了什么吗? > system.time(replicate(30000,sum(vapply(w,function(x)sum(x^2),numeric(1))))) 用户系统已用过 1.64 0.38 2.02 > system.time(replicate 30000,sum(unlist(w)^ 2))) user system elapsed 2.81 0.41 3.22 – Adam12344
@ Adam12344 - 我无法复制这些结果。 'vapply'的'0.84'秒和'unlist'的'0.07'秒 – thelatemail