%% Various views of meshgrid
%  HA 11.8.2016
%
% *meshgrid* is especially useful for 3d-graphics. Also in any
% computation where function defined on a 2d-mesh is required.
% 
% An easy illustration is to look at multiplication table.
%
%% First attempt: for-loop  
clear
close all
format compact
%%
x=1:5;
y=1:4;
%%
for i=1:5
    for j=1:4
        z(i,j)=i*j;
    end 
end
z
z'          % Matrix order (row-index goes down)
flipud(z')  % xy-order: row-index goes up
%%
% Thus we get the multiplication table in the form Matlab's graphics
% functions like mesh,surf,contour require. However, it is clumsy and
% ineffcient.
%% Using meshgrid
%
[X,Y]=meshgrid(x,y);
%
% Put X and Y side by side.
%%
[X Y]
%%
Z=X.*Y   % Multiplication table
%%
mesh(x,y,Z)
xlabel('x-axis')
ylabel('y-axis')
%% Handy ways to plot gridlines and gridpoints
% Look at X and Y side by side again:
%%
[X Y]
%%
% Look at X and Y as long column vectors side by side
%%
[X(:)  Y(:)]
%%
figure
plot(X(:),Y(:),'o')
%%
% The gridlines can also be seen most easily in 3d by
mesh(x,y,0*Z)
% You can look directly from above just rotating the figure
% with your mouse.
%
%% Example of surface plot
%
% Above we considered the function f(x,y)=x y. Instead we could have any
% function of 2 variables f(x,y)
% Let's take for instance
%%
% 
% $$f(x,y)=\sin(\frac{1}{\sqrt{0.1+x^2+y^2)}})$$
% 
figure
x=linspace(-2*pi,2*pi,30);
y=x;
[X,Y]=meshgrid(x,y);
Z=sin(1./sqrt(.1+X.^2+Y.^2));
mesh(x,y,Z)
%%
figure
surfc(x,y,Z),colorbar
xlabel('x-axis')
ylabel('y-axis')
%%
contour(x,y,Z,20)
%% Another example:
%
f = @(x,y) exp(cos(sqrt(x.^2 + y.^2))); % a function of two variables
d = -2*pi:0.1:2*pi;                     % domain for both x,y
[X,Y] = meshgrid(d,d);                  % create a grid of points
Z = f(X,Y);                             % evaluate f at every point on grid
surf(X,Y,Z);
shading interp;                         % interpolate between the points
material dull;                          % alter the reflectance
camlight(90,0);                         % add some light - see doc camlight
alpha(0.8);                             % make slightly transparent
box on;                                 % same as set(gca,'box','on')