Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude elements of Array based on index (Julia)

What is the most natural way to filter an array by index in Julia? The simplest example would be to leave off the kth element:

A = [1,2,3,4,5,6,7,8]
k = 4

[getindex(A, i) for i = 1:8 if i != k]

The above works but seems verbose compared to the simple A[-k] available in R. What's the cleanest way to perform this simple task?

like image 478
Richard Border Avatar asked Sep 26 '17 02:09

Richard Border


2 Answers

Not as terse as the R equivalent, but fairly readable:

A[1:end .!= k]

More importantly, this can be used in multidimensional arrays too, e.g.

B[  1:end .!= i,   1:end .!= j,   1:end .!= k  ]
like image 121
Tasos Papastylianou Avatar answered Sep 20 '22 20:09

Tasos Papastylianou


The simplest way is to use "Not".

julia> using InvertedIndices # use ] add InvertedIndices if not installed

julia> A = [1,2,3,4,5,6,7,8]

julia> k = 4;

julia> A[Not(k)]
7-element Array{Int64,1}:
 1
 2
 3
 5
 6
 7
 8
like image 41
Jayz Avatar answered Sep 18 '22 20:09

Jayz