1

I'm using Julia 1.0.3 and I'm attempting to run a line of code that was written in Julia 0.7. This line runs the base ifelse function along an array of boolean values. It appears that in this version of Julia, the ifelse function can no longer be run against a bitarray. Is there a way to get ifelse to work here?

x = collect(0:0.1:2) 
x2 = ifelse(2 .- 2*x.>=0, 2 .- 2*x, 0)

I'm expecting to get an array that shows 2-2x for all values of x>=0 and 0 otherwise. I am getting the following error.

TypeError: non-boolean (BitArray{1}) used in boolean context

Stacktrace:
 [1] top-level scope at In[67]:1
2
  • 1
    This code was likely written in Julia 0.5 or earlier — it was deprecated in Julia 0.6. If you run it there, Julia will happily give you the answer with a deprecation warning: WARNING: ifelse(c::AbstractArray{Bool}, x::AbstractArray, y) is deprecated, use ifelse.(c, x, y) instead. When updating code, it can be very helpful to walk through each version and fix the deprecation warnings as you go. Commented Jan 15, 2019 at 19:24
  • 2
    BTW, there is no reason to use collect. Just use the range 0:0.1:2 directly. Commented Jan 15, 2019 at 20:49

2 Answers 2

3

Just put a dot . after ifelse to broadcast. Many functions that operates on elements of collections require broadcasting with dot syntax on Julia 1.x.

x = collect(0:0.1:2) 
x2 = ifelse.(2 .- 2*x.>=0, 2 .- 2*x, 0.)
Sign up to request clarification or add additional context in comments.

Comments

2

Besides what others have mentioned, your code suffers from type instability problem. Use @code_warntype to verify this. x has elements of type Float64 and inside ifelse you have one branch with type Float64 and the other with type Int64. This can be solved by using zero(eltype(x)) instead of 0.

Instead of this strange condition 2 - 2*x >= 0, use this equivalent simple one x <= 1. Also, instead of broadcasting, I suggest using map which is faster and doesn't allocate. See below.

x = 0:0.1:2
x2 = map(x -> ifelse(x <= 1, 2 - 2x, zero(eltype(x))), x)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.