title: Remove duplicate key value pairs with tolerance by keeping the ones with largest value
body: <p>I am trying to remove duplicates with tolerance from a set of keys and values using the following rule:</p>
  
  <p>Assume the following set:</p>
  
  <pre><code>keys = [1 2 3 3.1 3.15 4 5];
  vals = [0.8 1 1.1 1.3 1.2 1 1.1];
  </code></pre>
  
  <p>Plotted this would look like this:
  <a href="https://i.stack.imgur.com/YOgD1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YOgD1.png" alt="Plotted key value pair"></a></p>
  
  <p>Now I would like to remove those pairs where the keys are very close together as indicated in the plot by the red circle. The key value pair that I would like to keep is that one with the largest value (in the example the middle one <code>[3.1; 1.3]</code>), so that the resulting set would be:</p>
  
  <pre><code>keys = [1 2 3.1 4 5];
  vals = [0.8 1 1.3 1 1.1];
  </code></pre>
  
  <p>I tried to use Matlab's <code>diff</code> function to get this behavior by doing</p>
  
  <pre><code>vals_new = keys(~(diff(keys) &lt; 0.5));
  keys_new = vals(~(diff(keys) &lt; 0.5));
  [M,I] = max(vals(diff(keys) &lt; 0.5));
  </code></pre>
  
  <p>This gives vals_new and keys_new as a new set that only includes the last of the duplicate pairs, but is also lacking the very last value:</p>
  
  <pre><code>keys_new = [1 2 3.15 4]
  vals_new = [0.8 1 1.2 1]
  </code></pre>
  
  <p>The last line returns the index of the maximum value of the duplicate pairs <code>I=2</code>, however does unfortunately not include the last of the three duplicate pairs <code>[3.15; 1.2]</code> so it's more a coincidence that it is correct here.</p>
  
  <p>I feel like there should be a much smarter way to do this, but can't really get my head around it.</p>