Monday, February 27, 2012

MATLAB: Surface plot of nonuniform data

It would be common to get a set of data: [X, Y, Z] for many simulations, and sometime I want to draw it "fancy" in Matlab, using either contour or 3-D surface plot. However, Matlab use a stupid "mesh" to do the job: when you want to draw a contour or surface, you need to run:

command(X, Y, Z), with X, Y, Z has the same size (n*n) dimension.

This is inconvenient for me, so I try to gather some information, how to easily generate a MESH for matlab from a 3-D xyz data.

(This blog is REALLY helpful: http://blogs.mathworks.com/pick/2007/11/02/advanced-matlab-surface-plot-of-nonuniform-data/, does this count a citation? ) 

1. Matlab ONLY use uniform data to do contour plot or surface plot

2. One need to generate a uniform data from the non-uniform data, so that matlab will plot it.


Suppose you save the xyz data into x, y, z, with a length N,

xlin = linspace(min(x),max(x),100);     
%  Generate 100 points linearly between (including) min(x) and max(x)

ylin = linspace(min(y),max(y),100);     
%  Generate 100 points linearly between (including) min(y) and max(y)

[X,Y]=meshgrid(xlin,ylin);
% Generate a MESH using the linear grid :) Finally, get the MESH in matlab

Z=griddata(x,y,z, X,Y,’cubic’);
% ZI = griddata(x,y,z,XI,YI) fits a surface of the form z = f(x,y) to the data in the (usually) nonuniformly spaced vectors (x,y,z). 
% Griddata interpolates this surface at the points specified by (XI,YI) to produce ZI.
% The surface always passes through the data points. 
% XI and YI usually form a uniform grid (as produced by meshgrid)
% The method defines the type of surface fit to the data. 
% The 'cubic' and 'v4' methods produce smooth surfaces while 'linear' and 'nearest' have discontinuities in the first and zero'th derivatives, respectively. 
% All the methods except 'v4' are based on a Delaunay triangulation of the data. If method is [], then the default 'linear' method is used.
% Keep in mind to use the 'cubic'  !!!

% Now you can check the surface and whether it is good generated :) 
mesh(X,Y,Z);
hold on
plot3(x,y,z, '*', 'MarkerSize',15)



Finally ~ No need to worry about this topic in the future:)


1 comment: