# Best way to convert a sparse (containing zeros) covariance matrix into a correlation matrix?

I have a $$100$$x$$100$$ covariance matrix that looks like this.

Some rows/cols are all-zero because those corresponding elements are not present in the sample from which covariance is calculated. I'm doing it this way:

    ...

fig, ax = plt.subplots()

def correlation_from_covariance(covariance):
v = np.sqrt(np.diag(covariance))
outer_v = np.outer(v, v)
correlation = covariance / outer_v                   <<<<<<      # complains here!
correlation[covariance == 0] = 0
return correlation

correlation = correlation_from_covariance(covariance)                # attempting to convert

im = ax.imshow(correlation)



When i try to get the correlation matrix, which i vaguely know to be the std-"normalized" version of covariance matrix, numpy complains : subunit_graph.py:218: RuntimeWarning: invalid value encountered in true_divide correlation = covariance / outer_v, but i still get a sensible correlation matrix. Can somebody explain to me what exactly is going on with true_divide in there?
Thank you very much!

• Apr 28, 2020 at 18:04

Dinv = np.diag(1.0 / np.sqrt(np.diag(cov_matrix)))