迭代器的foreach和非平行变化 [英] foreach and non-parallel change of iterators

查看:106
本文介绍了迭代器的foreach和非平行变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用两个相同大小的迭代变量(例如 1:n )执行,但函数会改变它们同时写成这里


我们将a和b称为迭代变量,因为这些是在多次执行过程中变化的变量。请注意,我们并行地迭代它们,也就是说,它们都在同时变化。

我需要的是使foreach独立地更改它们,以便我有一个长度 n ^ 2 的列表,而不是 n

例子:

  X = foreach(i = 1: n,j = 1:n)%do%(sum(M [i,] * M [j,]))

最后,我得到一个长度为 n 的向量,它只是矩阵X的对角线,而不是整个矩阵。
$ b

PS我试图使用 来进行 循环,但是计算时间过长,不能保证代码不被优化。 嵌套 foreach 循环,使用嵌套操作符%:%:

pre $ library $($ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $) X< - foreach(i = 1:n,.combine ='cbind')%:%
foreach(j = 1:n,.combine ='c')%do%{
sum (M [i,] * M [j,])
}

计算,你可以从 i n 迭代 j ,并使用 .final 函数将结果向量填充为 NA


$ b(b)= {pre $ pad < - 函数(x)c(rep(NA,n-长度(x)),x)
Y < - foreach = 1:n,.combine ='cbind')%:%
foreach(j = i:n,.combine ='c',.final = pad)%do%{
sum [i,] * M [j,])
}

但是这些解决方案只有学术兴趣。为了简单和快速,我怀疑 tcrossprod 是迄今为止最好的解决方案:

  Z < -  tcrossprod(M)

对于4000 X 4000矩阵,在我的Linux机器上不到8秒。


I need to execute foreach with two iteration variables of the same size (for example 1:n), but the function changes them in parallel as written here:

We call a and b the iteration variables, since those are the variables that are changing during the multiple executions. Note that we are iterating over them in parallel, that is, they are both changing at the same time.

What I need is to make foreach to change them independently, so that I would have a list with length n^2, not n.

example:

X = foreach(i=1:n, j=1:n) %do% (sum(M[i,]*M[j,]))

in the end I get a vector of length n which is only a diagonal of matrix X, not the full matrix.

P.S. I was trying to make this with for looping, but the computation time was too great to leave the code unoptimized.

解决方案

To nest foreach loops, use the nesting operator, "%:%":

library(foreach)
n <- 4
M <- matrix(rnorm(n*n), n)
X <- foreach(i=1:n, .combine='cbind') %:%
       foreach(j=1:n, .combine='c') %do% {
         sum(M[i,]*M[j,])
       }

To avoid repeated computations, you can have j iterate from i to n, and use a .final function to pad the resulting vectors with NA:

pad <- function(x) c(rep(NA, n - length(x)), x)
Y <- foreach(i=1:n, .combine='cbind') %:%
       foreach(j=i:n, .combine='c', .final=pad) %do% {
         sum(M[i,]*M[j,])
       }

But these solutions are only of academic interest. For simplicity and speed, I suspect that tcrossprod is the best solution by far:

Z <- tcrossprod(M)

For a 4000 X 4000 matrix, this executed in under 8 seconds on my Linux machine.

这篇关于迭代器的foreach和非平行变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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