# Plot a surface from data sets in MATLAB

I tried to plot a surface in MATLAB but, since it is the first time I had to do something like this, I need a confirmation on the process I followed because it is important for my project to plot the right surface.

I have 3 vectors obtained from measurement data: $x$ (displacement), $v$ (velocity) and $p$ (force). The goal is to plot a surface where $x$ and $v$ represent a point in the plane and $p$ is the "height" above that plane. The idea is to have a quite smooth surface, because then I have to fit this surface created from measurement data using a mathematical model.

This is what I have done:

first I create the grid: (since my measurements vectors have more than 400000 samples, do I have to use more than 1000 for x_plot and y_plot to have a good plot? I have also a problem when I increase too much the length of x_plot and y_plot, infact I get an "out of memory" error message)

x_plot = linspace(min(x),max(x),1000);
y_plot = linspace(min(v),max(v),1000);
[XI,YI] = ndgrid(x_plot,y_plot);


Then I create the scattered data interpolant:

F = TriScatteredInterp(x,v,p,'natural');


And now I evaluate the interpolant on the grid:

ZI = F(XI,YI);


Finally I plot the surface:

figure()
mesh(XI,YI,ZI)


Is this the right method?

Is it better to use ndgrid or meshgrid to create the grid?

• Thank you so much, Doug! I was looking for this far and wide! – user20771 Jun 22 '16 at 22:16

You may be better served with a slightly different method of surface plotting, especially if you're having memory issues. What you're doing right now is actually two separate things:

1. Interpolating your data onto a grid.

2. Plotting the surface corresponding to the interpolated data on the grid.

Since you have some raw data values which presumably do not line up with your grid this adds the additional errors associated with the interpolation. It also gives the appearance of having uniform data whether this is true or not.

Here is the approach I would take:

1. Generate a triangulation of your data points using delaunay

2. Use trisurf (or trimesh if you prefer) to plot the data using the triangulation

This has the advantage of directly plotting your data without requiring interpolation to a grid. It will also minimize the amount of memory used and eliminate the need to set a grid resolution.

Here's a minimal example:

clear all

% Number of points:
N = 10000;

% Generate some points:
x = 15*(rand(N,1)-.5);
y = 15*(rand(N,1)-.5);
z = cos(sqrt(x.^2+y.^2)).*exp(-0.025*(x.^2+y.^2));

% Delaunay triangulation:
tri = delaunay(x,y);

% Plot:
figure(1)
clf
trisurf(tri,x,y,z,'linestyle','none')
lighting p
camlight


If you prefer could use patch instead of trisurf:

figure(1)
clf
p.Faces=tri;
p.Vertices=[x, y, z];
p.FaceVertexCData=z;
patch(p)
view(3)