How to plot a covariance matrix on a 2D plot in MATLAB?
In MATLAB there is a function called cov
. If I insert a matrix X
into cov
like this cov(X)
, then cov
will return a square matrix of covariance.
My question is very simple:
How can I, with MATLAB, plot that matrix cov(X)
onto a 2D
plot like this.
I can see a lot of covariance matrix plots at Google. But how do they create them?
Solution 1:
My best guess is that you're trying to add the principal components to the plot. To do that, you could do something like this.
%% generate data points
S_tru = [2 1; 1 1];
N = 1000;
%% compute mean, covariance, principal components
X = mvnrnd([0,0],S_tru,N);
mu = mean(X);
S = cov(X);
[U,D] = eig(S);
%% specify base points/directions for arrows
base = [mu;mu];
vecs = sqrt(D)*U';
vecs = 2 * vecs;
%% plot
plot(X(:,1),X(:,2), 'r.')
axis equal
hold on
quiver(base(:,1),base(:,2),vecs(:,1),vecs(:,2),'blue','LineWidth',2)
Resulting graph: