cov(X,Y) is equivalent to cov([x(:) y(:)]). But [x(:) y(:)] is 20000 by 2 for you, and cov() treats rows as observations and columns as dimensions, so you get a 2 by 2 covariance matrix.

I would just implement it myself by the definition:

bsxfun(@minus,x,mean(x))'*bsxfun(@minus,y,mean(y))/(size(x,1)-1)

If you have an older version of matlab that doesn't support bsxfun(), just use repmat().

Answer from Yanshuai Cao on Stack Overflow
🌐
MathWorks
mathworks.com › signal processing toolbox
Correlation and Covariance - MATLAB & Simulink
They estimate covariance and normalized covariance respectively between the different channels at lag 0 and arrange them in a square matrix. You clicked a link that corresponds to this MATLAB command:
🌐
MathWorks
mathworks.com › matlabcentral › answers › 418761-how-to-calculate-covariance-matrix
How to calculate covariance matrix - MATLAB Answers - MATLAB Central
September 13, 2018 - It is my understanding that you ... one. Here is how we can achieve it. MATLAB has a function named "cov" that returns the covariance based on what is passed as parameters to the function....
🌐
GeeksforGeeks
geeksforgeeks.org › matlab › how-to-calculate-covariance-in-matlab
How to Calculate Covariance in MATLAB - GeeksforGeeks
July 23, 2025 - If A is a matrix, then it considers each column as a random variable and returns the covariance matrix of matrix A. Note: disp (x) displays the value of variable X without printing the variable name. Another way to display a variable is to type its name, which displays a leading “X =” before the value. If a variable contains an empty array, disp returns without displaying anything. Example 1: Matlab ·
Find elsewhere
🌐
Wikipedia
en.wikipedia.org › wiki › Covariance_matrix
Covariance matrix - Wikipedia
3 weeks ago - Indeed, from the property 4 it follows that under linear transformation of random variable X } with covariation matrix Σ X = c o v ( X ) } =\mathrm {cov} (\mathbf {X} )} by linear operator A } s.a. Y = A X =\mathbf {A} \mathbf {X} } , the covariation matrix is transformed as
🌐
Johns Hopkins University
math.jhu.edu › ~shiffman › 370 › help › techdoc › ref › cov.html
cov (MATLAB Function Reference)
Description C = cov(x) where x is a vector returns the variance of the vector elements. For matrices where each row is an observation and each column a variable, cov(x) is the covariance matrix. diag(cov(x)) is a vector of variances for each column, and sqrt(diag(cov(x))) is a vector of standard ...
🌐
MathWorks
mathworks.com › statistics and machine learning toolbox › anova › analysis of variance and covariance
Analysis of Covariance - MATLAB & Simulink
Using analysis of covariance, you can model y as a linear function of x, with the coefficients of the line possibly varying from group to group.
🌐
MathWorks
mathworks.com › matlabcentral › answers › 436387-how-do-i-create-and-calculate-a-covariance-matrix-how-do-you-get-the-covariance
how do i create and calculate a covariance matrix? how do you get the covariance - MATLAB Answers - MATLAB Central
December 18, 2018 - Create and calculate the values for a 5x5 matrix where the (i, j) component contains the covariance of the set of measurements from row i with the set of measurements from row j. Sign in to comment. Sign in to answer this question. ... Sign in to answer this question. Find more on Generate Test Data in Help Center and File Exchange ... Find the treasures in MATLAB Central and discover how the community can help you!
🌐
MathWorks
mathworks.com › matlabcentral › answers › 472122-covariance-matrix-and-principal-components
Covariance matrix and principal components - MATLAB Answers - MATLAB Central
July 17, 2019 - Then the eigenvectors (W) don't look like the analytic eigenvectors from the analytic covariance matrix. However if I instead calculate cov of realization_mat', the transposed, then the eigenvectors (W2) look like the analytic ones. However, on the help (https://la.mathworks.com/help/matlab/ref/cov.html) it is stated that the rows of A should be observations and the columns, variables; therefore, eig(cov(realization_mat)) should offer good eigenvectors, no teig(cov(realization_mat)).
🌐
MathWorks
mathworks.com › matlabcentral › answers › 477339-covariance-between-the-estimated-parameters-from-curve-fitting-toolbox
covariance between the estimated parameters from curve fitting toolbox - MATLAB Answers - MATLAB Central
August 23, 2019 - Thank you. with MSE and Jacobian from output Optimization Toolbox I can calculate covariance matrix. ... https://www.mathworks.com/matlabcentral/answers/477339-covariance-between-the-estimated-parameters-from-curve-fitting-toolbox#comment_1452777
Top answer
1 of 1
11

Note that numpy.cov() considers its input data matrix to have observations in each column, and variables in each row, so to get numpy.cov() to return what other packages do, you have to pass the transpose of the data matrix to numpy.cov().

The Python code that you linked can be used to simulate what other packages do, but it contains some errors: N should be the number of rows, not columns, and you have to perform the matrix multiplication in the other order:

import numpy as np

def cov(X0):
    print "\n==\nMatrix:"
    print X0
    X = X0 - X0.mean(axis=0)
    N = X.shape[0]                # !!!
    fact = float(N - 1)
    print "Covariance:"
    print np.dot(X.T, X) / fact   # !!!

X0 = np.vstack(([1, 2], [3, 4]))
cov(X0)
cov(X0.T)

X0 = np.vstack(([1, 2], [3, 4], [22, 44]))
cov(X0)
cov(X0.T)

With these fixes, the covariance behaves as expected:

==
Matrix:
[[1 2]
 [3 4]]
Covariance:
[[ 2.  2.]
 [ 2.  2.]]

==
Matrix:
[[1 3]
 [2 4]]
Covariance:
[[ 0.5  0.5]
 [ 0.5  0.5]]

==
Matrix:
[[ 1  2]
 [ 3  4]
 [22 44]]
Covariance:
[[ 134.33333333  274.33333333]
 [ 274.33333333  561.33333333]]

==
Matrix:
[[ 1  3 22]
 [ 2  4 44]]
Covariance:
[[   0.5    0.5   11. ]
 [   0.5    0.5   11. ]
 [  11.    11.   242. ]]

As for the numpy.linalg.svd() code, you need to center the data matrix by subtracting off the variable means, and the multiplication involving the V matrix must be performed in the other order. With these changes you will replicate everybody else's behavior:

import numpy as np

def cov(X0):
    print "\n==\nMatrix:"
    print X0
    X = X0 - X0.mean(axis=0)
    U, s, V = np.linalg.svd(X, full_matrices = 0)
    D = np.dot(np.dot(V.T,np.diag(s**2)),V)
    Dadjust = D / (X0.shape[0] - 1)
    print "Covariance:"
    print (Dadjust)
🌐
MathWorks
mathworks.com › phased array system toolbox › beamforming and direction of arrival estimation › beamforming
sensorcov - Sensor spatial covariance matrix - MATLAB
This MATLAB function returns the sensor spatial covariance matrix, xcov, for narrowband plane wave signals arriving at a sensor array.
🌐
MathWorks
mathworks.com › matlabcentral › answers › 1464934-how-to-obtain-the-3-x-3-symmetric-covariance-matrix-of-a-3x1-matrix
How to obtain the 3 × 3 symmetric covariance matrix of a 3x1 matrix? - MATLAB Answers - MATLAB Central
October 1, 2021 - So while the underlying process that generated the vector may have a well defined covariance matrix, you cannot compute it from one vector. You need more data. You cannot squeeze blood from a rock. Well, you might get blood if you try, but if you look at your hands, the blood came from your own fingers. Sorry. Sign in to comment. Sign in to answer this question. Find more on Matrix Indexing in Help Center and File Exchange ... Find the treasures in MATLAB Central and discover how the community can help you!
🌐
MathWorks
mathworks.com › matlabcentral › answers › 1610815-find-matrix-covariance-by-fitting-data-as-a-parabola
Find matrix covariance by fitting data as a parabola - MATLAB Answers - MATLAB Central
December 14, 2021 - In MATLAB, you can fit a parabola ... degree (2 for a parabola). You can also obtain the covariance matrix of the coefficients using the same function by requesting two output arguments....