Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select every nth element from an array in julia

Tags:

indexing

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?

like image 895
Fred Schoen Avatar asked Sep 22 '16 10:09

Fred Schoen


Video Answer


1 Answers

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}:
  ...
like image 139
Fred Schoen Avatar answered Sep 23 '22 21:09

Fred Schoen