【问题标题】:Fortran's do-loop over arbitary indices like for-loop in R?Fortran do-loop遍历任意索引,如R中的for循环?
【发布时间】:2012-03-19 16:22:16
【问题描述】:

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

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,所以有很多if 语句总是正确的。

在 R 中,我会这样做:

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 中那样做内循环?我确实尝试过这样的版本:

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 数组?

【问题讨论】:

    标签: r loops if-statement fortran


    【解决方案1】:

    如果您必须对大多数项目进行迭代,我认为无论如何您都不会获得显着的加速,而不是仅存储具有 0 值的整个数组的列表不是一种选择。您当然可以使用WHERE 或FORALL 构造。

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

    或者只是

    where(miss==0) z = ..
    

    但这些结构的通常限制适用。

    【讨论】:

    • 谢谢,我去看看 where 构造。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多