Hello Aishwarya,
The problem here is that the array x is 2x31 and does not have every possible combination of an element of X1 and an element of X2, which is 2x961. The method 2 code below fixes that by implementing the same idea as in method 1,
For method 2 to be correct you need the factor in front to be to the +1/2 power, since you have already put the factor into the denominator.
mu = [0,0];
sigma = [0.5 0.8; 0.8 2.0];
x1 = -3:0.2:3;
x2 = -3:0.2:3;
X = [x1; x2]
[X1,X2] = meshgrid(x1,x2);
X = [X1(:) X2(:)];
y = mvnpdf(X,mu,sigma);
y = reshape(y,length(x1),length(x2));
figure(1)
surf(X1,X2,y)
xlabel('x')
ylabel('y')
zlabel('Bivariate Gaussian Distributions')
mu = [0;0];
covar = [0.5 0.8; 0.8 2.0];
x1 = -3:0.2:3;
x2 = -3:0.2:3;
[X1,X2] = meshgrid(x1,x2);
X = [X1(:), X2(:)]';
arg = sum((X-mu).*(pinv(covar)*(X-mu)));
y2 = 1/(2*pi*(det(covar))^(1/2)) * exp(-(1/2)*arg);
y2 = reshape(y2,size(X1));
figure(2)
surf(X1,X2,y2)
xlabel('x')
ylabel('y')
zlabel('Bivariate Gaussian Distributions')
max(max(abs(y-y2)))
ans = 1.8041e-16
Best Answer