# Fortran do-loop over conditional indexes like for-loop in R?

I have two arrays p-times-n `x`

and `missx`

, where `x`

contains arbitrary numbers, and `missx`

is an array containing zeros and ones. I need to do recursive calculations at those points where it `missx`

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 `missx`

it is always 0, so there are quite a few operators `if`

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 `xlength`

and `whichx`

), but is there an even smarter way to do this like the R version so I wouldn't need to store those `xlength`

and `whichx`

arrays?

+2

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 `WHERE`

or `FORALL`

.

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

```

or simply

``````where(miss==0) z = ..
```

```

But the limitations of these constructs apply.

+5

source

All Articles