title: Showing 3D data on a patch surface with Matlab
body: <p>I want to show, with Matlab, a temperature distribution on an object surface.</p>
  
  <p>I've got a 3D data in the form of (x, y, z, V) vectors. I would like to show this object in Matlab, with the colour representing the local total "value". </p>
  
  <p>I can export the object as an STL file. It can be shown easily using the STL plotting (see <a href="http://nl.mathworks.com/matlabcentral/fileexchange/22409-stl-file-reader/content//STLRead/html/stldemo.html" rel="nofollow">stldemo</a>):</p>
  
  <pre><code>fv = stlread('file.stl');
  patch(fv, 'EdgeColor', 'none', 'FaceLighting', 'gouraud', 'AmbientStrength', 0.15, 'FaceColor', [0.8 0.8 1.0]);
  camlight('headlight');
  material('dull');
  </code></pre>
  
  <p>To colour it according to (x,y,z,V), I need to attach each (x, y, z) point to a vertex in the patch (the nearest one would work). If there are many (x,y,z) points for which a single STL vertex is the nearest, I add up the corresponding V values for that vertex.</p>
  
  <p>The number of vertices is thousands. The number of (x, y, z) points is also large. So doing a loop through (x, y, z) points and then an internal loop over vertices to find the nearest one (which involves calculating distances between points) is out of question. Is there any smart way to do it quickly?</p>
  
  <p>Note: I cannot control the location of the data points, they are defined by an external program. The STL points are controlled by another external program. So I have to marry two different point sets.</p>
  
  <p>Here is the code illustrating what I want to achieve, with 4 vertices and 3 data points:</p>
  
  <pre><code>% Create patch
  figure;
  p = patch;
  colorbar
  
  p.Vertices = [...
      0, 0, 0; ...
      1, 0, 0; ...
      1, 1, 0;
      0, 1, 0];
  p.Faces = [ ...
      1, 2, 3; ...
      1, 3, 4];
  
  % Data points
  x = [0.1, 0.1, 0.25];
  y = [0.01, 0.02, 0.75];
  z = [0.01, 0.2, -0.01];
  v = [1, 1, 1];
  
  p.FaceVertexCData = zeros(size(p.Vertices, 1), 1);
  % Point 1 (0.1, 0.01, 0.01) is closest to vertex 1 (0, 0, 0). Its value
  % goes to vertex 1.
  p.FaceVertexCData(1) = p.FaceVertexCData(1) + v(1);
  % Point 2 (0.1, 0.02, 0.2) is also closest to vertex 1 (0, 0, 0). Its
  % value also goes to vertex 1
  p.FaceVertexCData(1) = p.FaceVertexCData(1) + v(2);
  % Point 3 (0.25, 0.75, -0.01) is closest to vertex 4 (0, 1, 0). Its power
  % goes to vertex 4.
  p.FaceVertexCData(4) = p.FaceVertexCData(4) + v(3);
  % Other vertices are left with 0.
  
  p.FaceColor = 'interp';
  </code></pre>