Exclude index based array elements (Julia)

What is the most natural way to filter an array by index in Julia? The simplest example would be the rejection of the k-th 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 seem detailed compared to the simple ones A[-k]available at R. What is the cleanest way to accomplish this simple task?

+8
source share
4 answers

Not as short as the R equivalent, but readable enough:

A[1:end .!= k]

More importantly, it can also be used in multidimensional arrays, for example.

B[  1:end .!= i,   1:end .!= j,   1:end .!= k  ]
+10
source

Take a look deleteat!. Examples:

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

julia> deleteat!(A, k)
7-element Array{Int64,1}:
 1
 2
 3
 5
 6
 7
 8

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

julia> deleteat!(A, k)
4-element Array{Int64,1}:
 1
 3
 5
 7
+7
source

filter eachindex

julia> A = collect(1:8); println(A)        
[1, 2, 3, 4, 5, 6, 7, 8]                   

julia> A[ filter(x->!(x in [5,6]) && x>2, eachindex(A)) ]
4-element Array{Int64,1}:
 3
 4
 7
 8

If you apply a filter to each array size, you will need to replace eachindex(A)with indices(A,n), where nis the corresponding measurement, for example

B[ filter(x->!(x  in [5,6])&&x>2, indices(B,1)), filter(x->x>3, indices(B,2)) ]
0
source

Source: https://habr.com/ru/post/1686373/


All Articles