# Best way to avoid singular matrix crashing optimization routine

**URL:** <https://discourse.julialang.org/t/best-way-to-avoid-singular-matrix-crashing-optimization-routine/95897>\
**Category:** General Usage\
**Created:** [March 11, 2023, 12:04am UTC](https://discourse.julialang.org/t/best-way-to-avoid-singular-matrix-crashing-optimization-routine/95897 "2023-03-11T00:04:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jrhalket](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jrhalket/32/38750_2.png) [@jrhalket](https://discourse.julialang.org/u/jrhalket)\
**Post date:** [March 11, 2023, 12:04am UTC](https://discourse.julialang.org/t/best-way-to-avoid-singular-matrix-crashing-optimization-routine/95897/1 "2023-03-11T00:04:44Z")

</div>

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.

```julia
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?

---

<div class="post-metadata">

**Author:** ![mohamed82008](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mohamed82008/32/18171_2.png) [@mohamed82008](https://discourse.julialang.org/u/mohamed82008)\
**Post date:** [March 11, 2023, 12:18am UTC](https://discourse.julialang.org/t/best-way-to-avoid-singular-matrix-crashing-optimization-routine/95897/2 "2023-03-11T00:18:57Z")

</div>

```julia
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.
