Whats a better way to remove elements from an array based on index?```g = [55, 7

whats a better way to remove elements from an array based on index?

g = [55, 77, 88, 99, 3, 7, 8,99,99, 999]
ix_drop = 2:4
setdiff(g, g[ix_drop])

This works but it will remove duplicate values… and thats less than desirable…

Note that the original poster on Slack cannot see your response here on Discourse. Consider transcribing the appropriate answer back to Slack, or pinging the poster here on Discourse so they can follow this thread.
(Original message :slack:) (More Info)

deleteat!(g,ix_drop)

is the best solution (pointed on the slack thread, I am confused on now this works), but if one does not want to modify the original vector, but get a new one, one can do, for example:

julia> g[eachindex(g) .∉ Ref(ix_drop)]
7-element Array{Int64,1}:
  55
   3
   7
   8
  99
  99
 999

2 Likes

deletat! works fine on Julia Version 1.6.0-beta1.0:

g = [55, 77, 88, 99, 3, 7, 8,99,99, 999]
ix_drop = 2:4
deleteat!(g,ix_drop);
g
7-element Vector{Int64}:
  55
   3
   7
   8
  99
  99
 999

It does. It is just that it overwrites the original vector. That may or may not be wanted.

Sorry for misreading your post.
Another way in that case is to use setdiff:

g[setdiff(1:length(g), ix_drop)]
3 Likes

That is probably faster.

or just

g[setdiff(1:end, ix_drop)]

or even

g[setdiff(begin:end, ix_drop)]
3 Likes

This one looks nice too:

g[(begin:end) .∉ (ix_drop,)]

Interesting, although my reaction is begin and end of what?? Didn’t know that those keywords worked like that.

That comma breaks the magic… I prefer g[begin:end .∉ Ref(ix_drop)]
This one could go the the thread of syntatic sugars, if not because the setdiff is the fastest option.

1 Like

One thing I did not found in Base and implemented myself is the case in which you do not want to change the original vector, and you also want two new arrays, one for which the elements return true for some predicate, and the complement (i.e., the array for the values that evaluated false). Using two filter seemed terribly wasteful for me, it is a thing that theoretically needs a single sweep. So I wrote a small function that does that.

2 Likes