Condition on a whole array


#1

Hi,
I have a fairly simple question that would like to sort out with your kind help :slight_smile: The fact is that I like quite a lot the conditional syntax
{something} ? true : false
which works great for short decissions like

x>0.5 ? 1 : 0

Is it possible to do something similar not for scalar valued x but for x a vector or array? How would that be done? I understand that

x.>0

works, but what then? Of course I can use the map functionto do what I want, but was wondering if it is possible to do something simpler or performance wise (?)

Best regards and thanks,

Ferran.


#2

How about

[v > 0.5 ? 1 : 0 for v in x]

#3

The generator code above performs really well but ifelse seems to be even better:

julia> x = rand(100000);

julia> bar(x) = [v > 0.5 ? 1 : 0 for v in x]
bar (generic function with 1 method)

julia> @btime bar($x);
  103.453 μs (3 allocations: 781.34 KiB)

julia> foo(x) = ifelse.(x .> 0.5, 1, 0)
foo (generic function with 1 method)

julia> @btime foo($x);
  91.008 μs (2 allocations: 781.33 KiB)

#4

Ahhh… that seems to be a vairly simple way, thanks :slight_smile: I’ll test both ways and check what is better for my needs…


#5

One thing to keep in mind is that ifelse() and the ? operator are actually a bit different because ifelse evaluates both of its arguments, while ? only evaluates the argument chosen by the test. For example:

julia> function f(x)
         println("calling f")
         1
       end
f (generic function with 1 method)

julia> function g(x)
         println("calling g")
         2
       end
g (generic function with 1 method)

julia> y = true ? f(1) : g(1)
calling f
1

julia> y = ifelse(true, f(1), g(1))
calling f
calling g
1

It seems like this would make ifelse() always worse, but in fact the predictability of its behavior (always evaluating both arguments) can sometimes allow for more efficient pipelined code.


#6

Oh thanks.

But anyway, I still wonder if there is a ‘dot’ notation for the ?
operator… Something of the form

x == 0 .? true : false


#7

Regarding performance, you could try https://github.com/JuliaArrays/MappedArrays.jl.