%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% cplot is a tool for plotting level curves of a function
%%
%%     F(x,y)
%%
%%    levelcurve( F, x0, x1, y0, y1, vals)
%%
%%      F: the function to plot
%%  x0,x1: the range of x-coordinates
%%  y0,y1: the range of y-coordinates
%%   vals: A vector of function values determining the level curves to plot
%%
%%  Example:
%%
%%  F = @(x,y) x.^2 + y.^2
%%
%%  levelcurve(F,-2,2,-2,2,[0.5,1])
%%
%%  David Maxwell
%%  September 29, 2010

function levelcurve( F, x0, x1, y0, y1, vals)
  % Number of grid points for the plot
	Nx=500; Ny=500;

  % Test for correct vectorization:

  [x,y] = meshgrid( linspace(x0,x1,Nx),linspace(y0,y1,Ny));

  xv =  linspace(x0,x1,10);
  yv =  linspace(y0,y1,10);
  try
    Fxy = F(xv,yv);
    Fxy = F(x,y);
  catch e
    disp 'Function F appears to be broken.  Did you forget some dots?'
    disp 'Trying to continue using arrayfun.'
    Fxy = arrayfun(F,x,y);
  end

  if(exist('vals'))
    if(length(vals)==1)
      vals = [ vals(1), vals(1) ];
    end
    [c,h] = contour(x,y,Fxy,vals);
  else
    [c,h] = contour(x,y,Fxy);
  end
  clabel(c,h);
  axis([x0,x1,y0,y1])
  grid
  colormap cool
end
