Search code examples
numpycovariancevariance

why numpy variance of a matrix or vector gives a scalar


Updated: use np.cov instead, if you would like to get a matrix.

Given a vector vec= np.array([1,2,3,4]), why np.var(vec) return me a scalar instead of variance-covariance matrix in mathematics definiation?

This holds even after I force the vector to be column vector, vec_column = vec[:, np.newaxis], np.var(vec_columb) still gives a scalar instead of the usual definiation.

Also, given a matrix a = np.array([[1, 2], [3, 4]]) or a = np.matrix('1 2; 3 4'), why np.var(a) return me a scaler.


Solution

  • Use np.cov() for the covariance matrix. See the docs var and cov.