In general it's not a good idea to remove things from an array as you are 
looping over it. The while loop approach will be very slow for large 
arrays, especially if you need to remove a lot of items. 

To expand on what Milan said, it looks like you're currently using a 
condition to specify what to remove from the array. If you switch to using 
`filter!` then you will need do the opposite, which means specifying what 
to keep instead. So if your condition was previously something like (a[i] > 
1), you will need a function like f(x) = x <= 1 in `filter!`. 

On Tuesday, 9 February 2016 16:37:36 UTC, Milan Bouchet-Valat wrote:
>
> 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