% Plot a 2D Normal distribution given m and S.  The plot
% ranges for 2 standard deviations and uses 20 points in 
% each direction

function normal2d_plot (m,S)

   % Insure that m is in the proper form.

   if (columns (m) < rows (m))
      m = m';
   end

   % Get the range of values

   range = setrange (m,S);
   inc1 = (range(2,1) - range(1,1))/19;
   inc2 = (range(2,2) - range(1,2))/19;

   % Generate the x and y indices

   x = [range(1,1):inc1:range(2,1)];
   y = [range(1,2):inc2:range(2,2)];

   % Generate the mesh, calculate the probabilities and draw.
   % z is generated as a vector and needs to be reshaped.

   [X,Y] = meshgrid (x,y);
   z = normal2d_pdf ([X(:), Y(:)]', m, S);
   z = reshape (z, rows (X), columns (X));

   mesh (X,Y,z);

   endfunction

   function range=setrange (m, S)
 
     low1 = m(1) - 3 * sqrt (S(1,1));
     low2 = m(2) - 3 * sqrt (S(2,2));
     high1 = m(1) + 3 * sqrt (S(1,1));
     high2 = m(2) + 3 * sqrt (S(2,2));

     range = [low1 low2;high1 high2];
   endfunction

endfunction
