Fortran的do循环在R中的任意循环如for循环? [英] Fortran's do-loop over arbitary indices like for-loop in R?

查看:484
本文介绍了Fortran的do循环在R中的任意循环如for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个p-times-n数组 x missx ,其中 x 包含任意数字, missx 是一个包含零和1的数组。我需要对 missx 为零的点执行递归计算。显而易见的解决方案将如下所示:

I have two p-times-n arrays x and missx, where x contains arbitrary numbers and missx is an array containing zeros and ones. I need to perform recursive calculations on those points where missx is zero. The obvious solution would be like this:

do i = 1, n
   do j = 1, p
      if(missx(j,i)==0) then
         z(j,i) = ... something depending on the previous computations and x(j,i)
      end if
   end do
end do

这种方法的问题在于大部分时间 missx 始终为0,所以如果语句始终为真,则会有很多

Problem with this approach is that most of the time missx is always 0, so there is quite a lot if statements which are always true.

在R中,我会这样做:

In R, I would do it like this:

for(i in 1:n)
  for(j in which(xmiss[,i]==0))
     z[j,i] <- ... something depending on the previous computations and x[j,i]

有没有办法像Fortran那样执行内部循环?我曾尝试过这样的版本:

Is there a way to do the inner loop like that in Fortran? I did try a version like this:

do i = 1, n
   do j = 1, xlength(i) !xlength(i) gives the number of zero-elements in x(,i)
     j2=whichx(j,i) !whichx(1:xlength(i),i) contains the indices of zero-elements in x(,i)
     z(j2,i) = ... something depending on the previous computations and x(j,i)
   end do
end do

这看起来比第一个解决方案稍微快一些(如果不计算定义的数量 xlength whichx ),但有没有更像这个R版本更聪明的方法,所以我不需要存储那些 xlength 和 whichx 数组

This seemed slightly faster than the first solution (if not counting the amount of defining xlength and whichx), but is there some more clever way to this like the R version, so I wouldn't need to store those xlength and whichx arrays?

推荐答案

I如果你必须对大多数项目进行迭代,那么不要认为你会得到惊人的加速,而不是仅仅为整个数组存储0值的列表不是一种选择。您当然可以使用 WHERE FORALL 构造。

I don't think you are going to get dramatic speedup anyway, if you must do the iteration for most items, than storing just the list of those with the 0 value for the whole array is not an option. You can of course use the WHERE or FORALL construct.

forall(i = 1: n,j = 1: p,miss(j,i)==0) z(j,i) = ...

或者只是

or just

where(miss==0) z = ..

但是这些结构的适用限制适用。

But the ussual limitations of these constructs apply.

这篇关于Fortran的do循环在R中的任意循环如for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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