Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip errors in a loop for Julia

Tags:

julia

I want to skip an error during a loop in julia. The example is below. I want to calculate square root of each element in a vector. Since sqrt(-16) is a complex value, Julia will report error and stop the loop. I would like julia to continue the loop when there is an error in the loop. The output I am looking for is that result = [1, 2, 3, 99999, 5, 6] where 99999 indicates there is an error.

vec = [1,4,9,-16,25,36]
result = zeros(6)
for i = 1:6
  result[i] = sqrt(vec[i])
end

like image 465
Mizzle Avatar asked Dec 14 '22 10:12

Mizzle


2 Answers

A try/catch will intercept the error. Within the catch block, you can discard the error and return the sentinel value:

vec = [1,4,9,-16,25,36]
result = zeros(6)
for i = 1:6
    result[i] = try
        sqrt(vec[i])
    catch
        999999
    end
end

I assume this is a toy example. I will reiterate Julia's style guide: its best to avoid the error in the first place.

like image 91
David Varela Avatar answered Dec 16 '22 00:12

David Varela


In addition to the other answer which uses try / catch in the spirit of your question, you have a few more options. Probably the best approach would be:

function mysqrt(x)
    if x < 0
        999999.0
    else
        sqrt(x)
    end
end

vec = [1,4,9,-16,25,36]

julia> mysqrt.(vec)
6-element Array{Float64,1}:
      1.0
      2.0
      3.0
 999999.0
      5.0
      6.0

Though I would strongly suggest you not use 999999.0 as your sentinel value but instead use NaN or missing.

Another option available to you would be to lift vec to a Vector{Complex} so that you don't run into domain errors, but this will come at a performance cost. That would look like

julia> sqrt.(complex(vec))
6-element Array{Complex{Float64},1}:
 1.0 + 0.0im
 2.0 + 0.0im
 3.0 + 0.0im
 0.0 + 4.0im
 5.0 + 0.0im
 6.0 + 0.0im

and then you can filter the vector by real and imaginary parts as you wish.

like image 43
Mason Avatar answered Dec 16 '22 00:12

Mason