【发布时间】: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