Fused ternary operator?

Am I right there’s no “easy” way to broadcast the ternary operator? E.g.

x = [0,1,2]
@. x==0 ? 0. : 1/x   #this doesn't work

Of course, its easy enough to write the code yourself,

broadcast(x->(x==0 ? 0. : 1/x), [0,1,2])

But is there any way to do this more nicely already? Or is this a feature people would want?

What about broadcasting ifelse?

8 Likes

Ah did not know about that built-in, that’s basically exactly the nicer way to do it. Thanks!

I use an inline for loop and collect the result in an array
[x ==0 ? 0. : 1/x for x in [0,1,2]]

How does it work: “broadcasting ifelse”
in a simpel way?

The solution above would be, e.g.:

julia> x = [0,1,2]

julia> @. ifelse(x==0, 0., 1/x)
3-element Array{Float64,1}:
 0.0
 1.0
 0.5
1 Like

:grinning: Thank you

1 Like