Jou*_*ske 2 fortran loops if-statement r
我有两个p倍-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
Run Code Online (Sandbox Code Playgroud)
这种方法的问题在于大部分时间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]
Run Code Online (Sandbox Code Playgroud)
有没有办法在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
Run Code Online (Sandbox Code Playgroud)
这似乎比第一个解决方案稍快(如果不是数定义的数量xlength
和whichx
),但有一些更聪明的方式来这就像将R版本,所以我不会需要存储那些xlength
和whichx
阵列?
我不认为你会得到戏剧性的加速,如果你必须对大多数项目进行迭代,那么只存储整个数组的0值列表不是一个选项.你当然可以使用WHERE
或FORALL
构造.
forall(i = 1: n,j = 1: p,miss(j,i)==0) z(j,i) = ...
Run Code Online (Sandbox Code Playgroud)
要不就
where(miss==0) z = ..
Run Code Online (Sandbox Code Playgroud)
但这些结构的存在局限性适用.