12

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?

1 Answer 1

17

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}:
  ...
Sign up to request clarification or add additional context in comments.

4 Comments

Should mentioned that this is the same as MATLAB's notation.
I think the link to the :/colon-documentation has moved to here: docs.julialang.org/en/v1/base/math/#Base.::
fixed in the answer
This answer should probably highlight begin as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.