ifelse

ifelse(condition::Bool, x, y)

Return x if condition is true, otherwise return y. This differs from ? or if in that it is an ordinary function, so all the arguments are evaluated first. In some cases, using ifelse instead of an if statement can eliminate the branch in generated code and provide higher performance in tight loops.

Examples

julia> i = 10
       if i > 10
         println("i is bigger than 10.")
       elseif i < 10   
         println("i is smaller than 10.")
       else                    
       println("i is 10.")
       end
i is 10.
  1. Conditional assignment:

    julia> a = 10;
    julia> b = 20;
    julia> result = ifelse(a > b, "greater", "smaller")
    "smaller"

    The example assigns the value "smaller" to the variable result because the condition a > b is false.

  2. Replacing missing values:

    julia> values = [1, 2, missing, 4, missing];
    julia> replaced_values = ifelse.(ismissing.(values), 0, values)
    5-element Array{Union{Missing, Int64},1}:
    1
    2
    0
    4
    0

    This example uses broadcasting to replace missing values with 0 in an array.

  3. Performance optimization in loops:

    julia> function sum_positives(numbers)
              total = 0
              for num in numbers
                  total += ifelse(num > 0, num, 0)
              end
              return total
          end
    
    julia> sum_positives([-2, 5, -3, 7, 0])
    12

    In this example, ifelse is used within a loop to sum only the positive values. The use of ifelse instead of an if statement eliminates the branch, providing potential performance improvements.

Common mistake example:

julia> result = ifelse(10 > 5, "greater")
ERROR: MethodError: no method matching ifelse(::Bool, ::String)

The mistake here is that ifelse requires three arguments: the condition, the value for true, and the value for false. It's essential to provide all three arguments to ifelse for it to work correctly.

See Also

all, all!, angle, any, any!, falses, ifelse, is, isinf, isinteger, isnan, isperm, ispow2, isreal, trues,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: