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
just use continue:
for i = 1:n
iszero(i%500) && continue
result[i] = i
end
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With