You're really trying to do two things here. The first is, you have some random data and you want to fit it to a multivariate normal distribution. Your approach to this part works, although it can be streamlined:
n = 1000; d=2;
X = randn(n,2);
Get mean and covariance:
mumat=mean(X);
cov_mat=cov(X);
The second part is plotting the resulting distribution. Here you need a regular grid for your variables, not the random values you generated above:
x = -3:.2:3; y = -3:.2:3;
[X,Y] = meshgrid(x,y);
X = X-mumat(1); Y = Y-mumat(2);
Combine X and Y in a way that each row represents one 2D variable.
Now calculate the probabilities.
scale=((2*pi)^(d/2))*sqrt(abs(det(cov_mat)));
p = zeros(length(Z),1);
for ii=1:length(Z)
p(ii) = exp(-Z(ii,:)/cov_mat*Z(ii,:)'/2)/scale;
end
Reshape and plot.
p = reshape(p,length(x),length(y));
surf(x,y,p)
xlabel('x'), ylabel('y')
Best Answer