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

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