我有两个 p-times-n 数组 x
和 missx
,其中 x
包含任意数字,missx
> 是一个包含 0 和 1 的数组。我需要对 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
语句始终为 true。
在 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
数组?
最佳答案
我认为无论如何,如果您必须对大多数项目进行迭代,那么您不会获得显着的加速,而不是仅存储整个数组的值为 0 的项目的列表。您当然可以使用 WHERE
或 FORALL
构造。
forall(i = 1: n,j = 1: p,miss(j,i)==0) z(j,i) = ...
或者只是
where(miss==0) z = ..
但是这些构造通常存在局限性。
关于r - Fortran do-loop 任意索引,如 R 中的 for-loop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9773872/