Coastlines/NearestValue.m

24 lines
843 B
Matlab

function [idx,difference,gridVal] = NearestValue(val,gridX,gridY)
%% Function to find the nearest point in in a 1D or 2D array.
% Works with a 2D array of X and Y points, given a nearest
% X,Y point to find
% Alexander Rey, Queen's University, Jan 2019
if min(size(gridX)) == 1 % if 1D
tmp = abs(gridX - val); %Find the difference between array and values
[difference, idx] = min(tmp); %Use the index with the smallest diffference
gridVal = gridX(idx);
else %if 2D
tmpX = abs(gridX - val(1));
tmpY = abs(gridY - val(2));
[diffsX,rowsX] = min(tmpX+tmpY); %Create and array of the difference in each row
[diffsY,rowY] = min(diffsX);
idx = [rowsX(rowY) rowY];
difference = [gridX(idx(1),idx(2))-val(1) gridY(idx(1),idx(2))-val(2)];
gridVal = [gridX(idx(1),idx(2)) gridY(idx(1),idx(2))];
end
end