Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

julia

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
like image 360
Mizzle Avatar asked Oct 23 '25 09:10

Mizzle


2 Answers

just use continue:

for i = 1:n
  iszero(i%500) && continue
  result[i] = i
end
like image 65
jling Avatar answered Oct 25 '25 22:10

jling


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)
like image 37
rashid Avatar answered Oct 26 '25 00:10

rashid