Stuart’s MATLAB Videos

Watch and Learn

Revisited: Integrating to find the volume underneath a set of non uniformly spaced data

Well, am I turning red! Soon after I posted my last video about how to find the volume underneath a set of non uniformly spaced data, I found one of our developers had a better way to do it using features of the newly released MATLAB 2009b.

Here is the video again:

Let’s repeat the code here from the beginning

n = 10;
randOffset = 0.1;
h = 1;
x = rand(n);
x(1:4)=[0 1 0 1]';
y = rand(n);
y(1:4)=[0 0 1 1]';
z = h + randOffset*rand(n) - randOffset/2; %make average height
axis equal
zlim([0 h + randOffset])

Now, the new feature being used is the fit command from the Curve Fitting Toolbox:

sf = fit( [x(:), y(:)], z(:), 'linearinterp' )

     Linear interpolant:
       sf(x,y) = piecewise linear surface computed from p
       p = coefficient structure

Then the volume is found using more or less the same call to QUAD2D. I told you it was cool:

vol = quad2d( sf, 0, 1, 0, 1 )

vol =

Caveats You’ll notice that I had appended some “special points” to this data set. This is so that we can interpolate into the corners. The “fit object”, sf, will suffer the same problem as it is built on top of GRIDDATA. Another way around this issue is to use a scheme that extrapolates,

  • Use a different interpolation scheme, e.g., ‘nearest’/ ‘nearestinterp’ or ‘v4’/ ‘biharmonicinterp’ (I’d use the latter because it is the best). This will work for both fit and GRIDDATA.
  • Fit the data in a least squares sense, e.g., using ‘lowess’.
Extrapolation should be OK in this case as we are not extrapolating too far from the data.
Sometimes, I think I write this blog so that *I* can learn more MATLAB from the people that read it! Your comments and suggestions are always welcome below!
  • print


To leave a comment, please click here to sign in to your MathWorks Account or create a new one.