Fred Schoen
Fred Schoen

Reputation: 1432

Select every nth element from an array in julia

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?

Upvotes: 12

Views: 8007

Answers (1)

Fred Schoen
Fred Schoen

Reputation: 1432

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}:
  ...

Upvotes: 17

Related Questions