Skip to content

Instantly share code, notes, and snippets.

@kwikwag
Created June 9, 2013 23:01
Show Gist options
  • Select an option

  • Save kwikwag/5745627 to your computer and use it in GitHub Desktop.

Select an option

Save kwikwag/5745627 to your computer and use it in GitHub Desktop.
Creates a matrix with the same dimensions as 'needle', placing in each element the closest value from 'haystack'; thanks to http://stackoverflow.com/users/279858/bill-cheatham
function [val, i] = closest(haystack, needle)
[~, i] = min(abs( ...
repmat(reshape(haystack,numel(haystack),1),1,numel(needle)) - ...
repmat(reshape(needle,1,numel(needle)),numel(haystack),1) ...
), [], 1);
val = reshape(haystack(i), size(needle));
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment