# Evaluating a MvNormal density with a sparse covariance matrix

**URL:** <https://discourse.julialang.org/t/evaluating-a-mvnormal-density-with-a-sparse-covariance-matrix/98173>\
**Category:** Performance\
**Tags:** question\
**Created:** [May 1, 2023, 7:42pm UTC](https://discourse.julialang.org/t/evaluating-a-mvnormal-density-with-a-sparse-covariance-matrix/98173 "2023-05-01T19:42:20Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![schwob](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/schwob/32/49423_2.png) [@schwob](https://discourse.julialang.org/u/schwob)\
**Post date:** [May 1, 2023, 7:42pm UTC](https://discourse.julialang.org/t/evaluating-a-mvnormal-density-with-a-sparse-covariance-matrix/98173/1 "2023-05-01T19:42:20Z")

</div>

Suppose that Q is a sparse covariance matrix, and I want to evaluate \mathbf{y} \sim N(\boldsymbol{0},Q). Can I leverage the sparsity of Q? Right now, I have Q as a `SparseMatrixCSC{Float64, Int64}`. Roughly 97% of the matrix is 0.

When I use `pdf(MvNormal(zeros(n), Q), y)`, I get the following error: `MethodError: no method matching PDMats.PDMat(::SparseMatrixCSC{Float64, Int64}, ::SuiteSparse.CHOLMOD.Factor{Float64})`. It seems that `MvNormal()` does not accept a sparse matrix as the covariance matrix because of some incompatibility in the `PDMats` package. For the time begin, I am using `pdf(MvNormal(zeros(n), Hermitian(Array(Cov_y_star))), y)`. However, this seems incredibly inefficient.

Do you know of a way that I can leverage the sparsity of Q to improve the computational speed in evaluating a multivariate normal distribution?

---

<div class="post-metadata">

**Author:** ![ElOceanografo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/eloceanografo/32/624_2.png) [@ElOceanografo](https://discourse.julialang.org/u/ElOceanografo)\
**Post date:** [May 1, 2023, 9:09pm UTC](https://discourse.julialang.org/t/evaluating-a-mvnormal-density-with-a-sparse-covariance-matrix/98173/2 "2023-05-01T21:09:55Z")

</div>

You need to explicitly wrap Q as a `PDSparseMat`. I’m not sure why there isn’t an outer constructor for `MvNormal` that converts to `PDSparseMat` automatically, but regardless, the following should work:

```julia
using Distributions, PDMats, SparseArrays
Q = spdiagm(ones(10))
d = MvNormal(PDSparseMat(Q))
logpdf(d, randn(10))

```
