I'm trying to generate a 2D Gaussian kernel in MatLab. I found two ways to do it.
1. Using mvnpdf
mu = [0 0];
sigma = 1.4;
sigma_mat = 1/sigma^2 * eye(2);
x1 = -3:1:3;
x2 = x1;
[X1,X2] = meshgrid(x1,x2);
G = mvnpdf([X1(:) X2(:)],mu,sigma_mat);
F = reshape(G,length(x2),length(x1));
This gives the below matrix
0 0 0 0 0 0 0
0 0 0 0.01 0 0 0
0 0 0.04 0.12 0.04 0 0
0 0.01 0.12 0.31 0.12 0.01 0
0 0 0.04 0.12 0.04 0 0
0 0 0 0.01 0 0 0
0 0 0 0 0 0 0
- Using fspecial('gaussian')
f = fspecial('gaussian', [7,7], 1.4);
This gives the matrix as
0.00 0.00 0.01 0.01 0.01 0.00 0.00
0.00 0.01 0.02 0.03 0.02 0.01 0.00
0.01 0.02 0.05 0.06 0.05 0.02 0.01
0.01 0.03 0.06 0.08 0.06 0.03 0.01
0.01 0.02 0.05 0.06 0.05 0.02 0.01
0.00 0.01 0.02 0.03 0.02 0.01 0.00
0.00 0.00 0.01 0.01 0.01 0.00 0.00
What is the difference between these 2 functions? Why are they giving different outputs?
Thanks!
Edit 1: As Cris Luengo rightly pointed out, there was an error in sigma_mat
. It should be
sigma_mat = sigma^2 * eye(2);
Even after that, there are some minor differences in decimal points.