Fortran do-loop over conditional indexes like for-loop in R?
I have two arrays p-times-n
contains arbitrary numbers, and
is an array containing zeros and ones. I need to do recursive calculations at those points where it
is zero. The obvious solution would be:
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
The problem with this approach is that most of the time
it is always 0, so there are quite a few operators
that are always correct.
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]
Is there a way to make an inner loop like in Fortran? I tried 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
This seemed a bit faster than the first solution (aside from the number of defining
), but is there an even smarter way to do this like the R version so I wouldn't need to store those
source to share
I don't think you will get a dramatic speedup anyway if you want to iterate over most of the elements, rather than just keeping a list of those that have 0 for the entire array is not an option. You can of course use the construct
forall(i = 1: n,j = 1: p,miss(j,i)==0) z(j,i) = ...
where(miss==0) z = ..
But the limitations of these constructs apply.
source to share