How to index all but select indices?

2020-02-10 15:47发布

问题:

I have an array a=rand(100), I want to get every value except the values at the indices notidx=[2;50]. Is there a clean way to get a at the other values? I am looking for a good way to do both a copy and a view.

Currently I make the array [1;3:49;51:100] by symdiff(1:100,notidx), but a[symdiff(1:length(a),notidx)] and view(a,a[symdiff(1:length(a),notidx)]) are not very clean (or understandable to others) ways of doing this.

回答1:

I don't have anything super clean, but you can do

a[setdiff(1:end, notidx)]

which is slightly cleaner than what you had, or

ind = trues(length(a))
ind[notidx] = false
a[ind]

which is pretty verbose but very clear.



回答2:

Update:

If you are using julia-v0.5+, you can also use the new generator expression, for example:

view(a, [i for i in indices(a)... if i ∉ notidx])

and

[a[i] for i in indices(a)... if i ∉ notidx]

Old post:

To get a copy, you can firstly make a copy of a, then manipulate it with deleteat! to delete those values at specific indices. After you've done this, it's convenient to get a view of a via indexin:

a = rand(100)         
# => 100-element Array{Float64,1}:
 0.62636  
 0.488919 
 0.499884 
 ....

b = copy(a)           
deleteat!(b, [2,50])  
# => 98-element Array{Float64,1}:
 0.62636  
 0.499884 
 ....


标签: arrays julia