Let's say have an array a
and I want every other element. With numpy
, I would use a[::2]
. How can I do the same in julia?
It is similar to python where elements are selected using start:stop[:step]
but in julia it's start:[step:]stop
, so if all three arguments are given, step
and stop
have opposite meaning. See the docs on :
or colon
For example
julia> a = randn(20);
julia> a[1:2:end]
10-element Vector{Float64}:
...
julia> a[begin:2:end] # equivalent for default one-based indexing
10-element Vector{Float64}:
...
julia> a[1:5:end]
4-element Vector{Float64}:
...
But ignoring the bounds won't work as in python because :
has several meanings in julia
julia> a[::2]
ERROR: syntax: invalid "::" syntax
julia> a[:2:]
ERROR: syntax: missing last argument in ":(2):" range expression
julia> a[2::]
ERROR: syntax: unexpected "]"
julia> a[:2:end] # `:2` is a `Symbol` and evaluates to `2`, so start from 2nd element
19-element Vector{Float64}:
...
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