% surf, patch, meshgrid example
clear all;close all;
% want to plot a surface z=f(x,y)
% need to evaluate z at each point (x,y) in a grid of points
x=[0:4]; %5 points
y=[-1:2]; % 4 points
% we want to plot z over the range specified by x and y.

[X,Y]=meshgrid(x,y); % makes two matrices X and Y.
% the two matrices seen together make up the 5x4=20 pairs of points (x,y)
% so there are 20 values of x and 20 values of y 
% (x,y) pairs of points in a grid
% (0,2)  (1,2)  (2,2)  (3,2)  (4,2)
% (0,1)  (1,1)  (2,1)  (3,1)  (4,1)
% (0,0)  (1,0)  (2,0)  (3,0)  (4,0)
% (0,-1) (1,-1) (2,-1) (3,-1) (4,-1)
% the X matrix is all the x-coordinates of this grid 
X
% the Y matrix is all the y-coordinates of this grid
Y
% now evaluate a surface function z=f(x,y) at each of the 20 points
Z=X+Y;
% the Z matrix is all the z-coordinates that go with the (x,y) pairs
figure(1)
mesh(X,Y,Z);
figure(2)
surf(X,Y,Z);

% separate example, meshgrid with a different syntax
[x3,y3] = meshgrid([-2:.2:2]);
Z3 = x3.*exp(-x3.^2-y3.^2);
figure(3)
surf(x3,y3,Z3,gradient(Z3))
% the 4th coordinate in surf is represented by color
% in this example, the gradient is represented in color
colorbar % shows the scale, which color corresponds to which value of the gradient