% IAP 2006 Introduction to MATLAB
% Interface and Basics

% EXAMPLE 3 Surface Interpolation

% A. Data Import

% A1. Import of X, Y, Z (irregular mesh points) from file XYZ_point_coordinates.txt
% Open the Import Wizard from the File->Import Data... menu.
% Select file XYZ_point_coordinates.txt.
% Toggle on option Create Vectors From Each Column Using Column Names.
% Three vectors are created: X, Y, Z; check the variables:
whos

% A2. Plot the points in 3d using a red circle symbol.
plot3(X, Y, Z, 'ro')

% B. Interpolation of the surface on a regular grid

% B1. Create a regular x, y grid using the built-in meshgrid function
% The grid covers the same area as the X, Y area of the imported mesh.
[x, y] = meshgrid([-3000:100:3000], [-3000:100:3000])

% B2. Interpolate a surface over the x,y grid using the built-in griddata function.
% The surface interpolates between the control points defined by (X, Y, Z).
z = griddata(X, Y, Z, x, y)
% griddata uses cubic spline as default interpolation.
% Alternatively, use the "nearest neighbor" method for interpolation:
z1 = griddata(X, Y, Z, x, y, 'nearest')

% B3. Plot surfaces and points
surf(x, y, z)
% Add the original control points to the same gragh:
hold on
plot3(X, Y, Z, 'wo')
hold on
% Add graph anotation (optional - more on that in the Graphics session)
xlabel('x'); 
ylabel('y');
zlabel('Depth')
title('Surface Interpolation from Points')

% B4. Figure and Data Export
% Save the figure created in B3:
% From the Figure editor, use File->Save As.
% Save the figure as surface.fig (a MATLAB format) and as surface.jpg.

% Save the interpolated surface's coordinates in text files
% We shall use these filess later in the session on Graphics. 
save grid_x.dat x -ascii
save grid_y.dat y -ascii
save interp_spline_z.dat z -ascii

% C. Try computing and plotting other things
% For example, try computing and plotting the difference between the cubic
% spline and the nearest neighbor interpolated surfaces.
% Or use your own point data sets to create interpolated surfaces.





