Mizzle
Mizzle

Reputation: 757

In Julia, how to skip certain numbers in a for loop

In the julia for loop, I want to skip the numbers that can be divided by 500. For example, in the loop below, I want to skip i=500, 1000, 1500, 2000, 2500, ..., 10000. How can I do that?

n=10000
result = zeros(n)
for i = 1:n
  result[i] = i
end

Upvotes: 4

Views: 2164

Answers (3)

rashid
rashid

Reputation: 664

A more efficient option than continue would be to use Iterators.filter to create a lazy iterator which filters the values you don't require.

For the example given in the OP, this would be:

n=10000
result = zeros(n)
iter = Iterators.filter(i -> (i % 500) != 0, 1:n)
for i = iter
  result[i] = i
end

A benchmark comparing with @jling's answer:

julia> @btime for i = 1:n
         iszero(i%500) && continue
         result[i] = i
       end
  1.693 ms (28979 allocations: 609.06 KiB)

julia> @btime for i = iter
         result[i] = i
       end
  1.177 ms (28920 allocations: 607.81 KiB)

Upvotes: 1

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42234

While the answer by @jing is perfectly correct, sometimes you have a list of values that you want to actually skip. In such cases Not may be an elegant solution:

julia> skipvals = [2,4,5];

julia> for i in (1:7)[Not(skipvals)]
       print("$i ")
       end
1 3 6 7

Not is a part of the InvertedIndices package, but also gets imported together via DataFrames, so in most data science codes it is just there for you to use :)

Upvotes: 0

jling
jling

Reputation: 2301

just use continue:

for i = 1:n
  iszero(i%500) && continue
  result[i] = i
end

Upvotes: 3

Related Questions