# Best way to avoid singular matrix crashing optimization routine

I have a log likelihood function I’m trying to maximize and as part of the computation of the log likelihood I call a function `ScalcAll` which performs the following calcs, including inverting a matrix. `up` and `down` are data and the other inputs are the parameters for which I’m trying to find an an argmin numerically.

``````function ScalcAll(up::SVector{2,Float64},dn::SVector{2,Float64},rΣ,θ_0,θ_1,θ_2)
ats = SVector{2, Float64}
ats = [up'*(θ_0 + θ_1)*dn ; up'*(θ_0 + θ_2)*dn]
0.5*ats'*((hcat(ats,ats)+rΣ)\ats)
end
``````

The issue is that for some sets of parameter values, I get a singular matrix error, ending my optimization routine. Given that I have no apriori idea which parameter values might do this, what’s the best way to efficiently (speed-wise) avoid this crashing my program?

``````T = eltype(rΣ) # make sure it's the type of the output
F = lu(hcat(ats, ats) + rΣ, check = false) # avoids the error
issuccess(F) || return T(Inf) # assuming minimization, this step will be rejected
return 0.5 * ats' * (F \ ats)
``````

can also use `cholesky` instead of `lu` if the matrix is symmetric positive definite.