Plot a grid of Gaussians with Matlab

Matteo picture Matteo · Dec 1, 2012 · Viewed 18k times · Source

With the following code I'm able to draw the plot of a single 2D-Gaussian function:

x=linspace(-3,3,1000);
y=x';               
[X,Y]=meshgrid(x,y);
z=exp(-(X.^2+Y.^2)/2);
surf(x,y,z);shading interp

This is the produced plot:

enter image description here

However, I'd like to plot a grid having a specified number x of these 2D-Gaussians. Think of the following picture as an above view of the plot I'd like to produce (where in particular the grid is made of 5x5 2D-Gaussians). Each Gaussian should be weighed by a coefficient such that if it's negative the Gaussian is pointing towards negative values of the z axis (black points in the grid below) and if it's positive it's as in the above image (white points in the grid below).

enter image description here

Let me provide some mathematical details. The grid corresponds to a mixture of 2D-Gaussians summed as in the following equation:

enter image description here

In which each Gaussian has its own mean and deviation.

Note that each Gaussian of the mixture should be put in a determined (X,Y) coordinate, in such a way that they are equally distant from each other. e.g think of the central Gaussian in (0,0) then the other ones should be in (-1,1) (0,1) (1,1) (-1,0) (1,0) (-1,-1) (0,-1) (1,-1) in the case of a grid with dimension 3x3.

Can you provide me (and explain to me) how can I do such a plot? Thanks in advance for the help.

Answer

Acorbe picture Acorbe · Dec 1, 2012

Indeed you said yourself, put (as an example just for the means)

[X,Y]=meshgrid(x,y);  % //mesh

g_centers = -3:3;    
[x_g,y_g] = meshgrid(g_centers,g_centers); % //grid of centers (coarser)
mu = [x_g(:) , y_g(:)];  % // mesh of centers in column


z   = zeros(size(X));
for i = 1:size(mu,1)
     z= z + exp(-((X-mu(i,1)).^2+(Y-mu(i,2)).^2)/( 2* .001) );
end
surf(X,Y,z);shading interp

enter image description here