title: Fix offset points to grid in MATLAB
body: <p>I have points that are mostly on a 3d grid. The spacing is known in all cases (spacing = 0.2,0.2,0.25) but the start/end coordinates can be different in each case.</p>
  
  <p>There are a few points that are slightly offset from the grid.</p>
  
  <p>e.g. an offset point in the z direction
  1,1,0.75; 1,1,1; <strong>1,1,1.1</strong>; 1,1,1.25; 1,1,1.5</p>
  
  <p>I am struggling to find an efficient way to fix these offset point to their nearest 'correct' location. Specifically how to handle cases where it is the minimum or maximum coordinate that is offset from the grid</p>
  
  <p>My approach...</p>
  
  <pre><code>duo = sortrows(duo,1);
  a = diff(duo(:,1));
  b = find(a&gt;0.00001 &amp; abs(a-0.2)&gt;0.00001);
  if mod(length(b),2) == 1
      display('Grid issue. Failing...');
      return;
  end
  for i=1:2:length(b)
      if abs(duo(b(i),1)-duo(b(i)+1,1)) &lt; abs(duo(b(i+1),1)-duo(b(i+1)+1,1))
          for j=b(i)+1:b(i+1)
              duo(j,1) = duo(b(i),1);
          end
      else
          for j=b(i)+1:b(i+1)
              duo(j,1) = duo(b(i+1)+1,1);
          end
      end
  end
  
  duo = sortrows(duo,2);
  a = diff(duo(:,2));
  b = find(a&gt;0.00001 &amp; abs(a-0.2)&gt;0.00001);
  if mod(length(b),2) == 1
      display('Grid issue. Failing...');
      return;
  end
  for i=1:2:length(b)
      if abs(duo(b(i),2)-duo(b(i)+1,2)) &lt; abs(duo(b(i+1),2)-duo(b(i+1)+1,2))
          for j=b(i)+1:b(i+1)
              duo(j,2) = duo(b(i),2);
          end
      else
          for j=b(i)+1:b(i+1)
              duo(j,2) = duo(b(i+1)+1,2);
          end
      end
  end
  
  duo = sortrows(duo,3);
  a = diff(duo(:,3));
  b = find(a&gt;0.00001 &amp; abs(a-0.25)&gt;0.00001);
  if mod(length(b),2) == 1
      display('Grid issue. Failing...');
      return;
  end
  for i=1:2:length(b)
      if abs(duo(b(i),3)-duo(b(i)+1,3)) &lt; abs(duo(b(i+1),3)-duo(b(i+1)+1,3))
          for j=b(i)+1:b(i+1)
              duo(j,3) = duo(b(i),3);
          end
      else
          for j=b(i)+1:b(i+1)
              duo(j,3) = duo(b(i+1)+1,3);
          end
      end
  end
  </code></pre>