The problem is that condition is a bit more complicated acctually. I have 
an array of composite type elements and condition includes not only current 
i-th element's properties, but also some other elements. Moreover, for some 
purpose I need to swap my i-th element with last element before removing it 
(so basicly every time I remove the last element). So I guess removing 
elements one-by-one is my only option. But thank you for your advices, I 
will certainly use them in future!

вторник, 9 февраля 2016 г., 19:37:36 UTC+3 пользователь Milan Bouchet-Valat 
написал:
>
> Le mardi 09 février 2016 à 08:04 -0800, Aleksandr Mikheev a écrit : 
> > Hi everyone.  
> > 
> > Suppose I have the array called a. And I need to check all of its 
> > ellements on the some condition. Further, I need to remove those 
> > ellements which satisfy the condition. I know I can do this using 
> > operator 'while'. Something like this: 
> > 
> > i = 0 
> > while (i < length(a)) 
> > i = i + 1 
> > if (condition on a[i]) 
> > splice!(a, i) 
> > i = i - 1 
> > end 
> > end 
> > 
> > But I've heard that using operator 'while' is quite slower than using 
> > 'for'-loop. So is there any better way to do what I need to do? 
> I don't know where you've heard that, but that's wrong in general. In 
> the present case, what's likely going to be slow is removing elements 
> one-by-one, which involves moving all following elements repeatedly. A 
> faster strategy would be to copy elements to retain, which is what 
> filter!() does in Base: 
> https://github.com/JuliaLang/julia/blob/4895ef64fb1a3c2f0ac3e073b2f236f 
> 5e603d536/base/array.jl#L870 
> <https://github.com/JuliaLang/julia/blob/4895ef64fb1a3c2f0ac3e073b2f236f5e603d536/base/array.jl#L870>
>  
>
> You can use filter!() instead of writing the loop yourself. For 
> example, if the condition is > 1, do: 
> a = [1, 2, 3] 
> filter!(x->x > 1, a) 
>
> But anonymous functions are slow in 0.4 (fixed in 0.5), so you would need 
> to do: 
> f(x) = x > 1 
> filter!(f, a) 
>
>
> You can also use indexing if you don't mind taking a copy: 
> cond = Bool[x > 1 for x in a] 
> a[cond] 
>
> Finally, if the condition only involves arithmetic operators with 
> element-wise versions, you can also write: 
> a[a .> 1] 
>
>
>
> Regards 
>

Reply via email to