Home > matGeom > geom2d > findClosestPoint.m

findClosestPoint

PURPOSE ^

FINDCLOSESTPOINT Find index of closest point in an array.

SYNOPSIS ^

function [index, minDist] = findClosestPoint(coord, points)

DESCRIPTION ^

FINDCLOSESTPOINT Find index of closest point in an array.

   INDEX = findClosestPoint(POINT, POINTARRAY)

   [INDEX, MINDIST] = findClosestPoint(POINT, POINTARRAY)
   Also returns the distance between POINT and closest point in
   POINTARRAY.

   Example
     pts = rand(10, 2);
     findClosestPoint(pts(4, :), pts)
     ans =
         4

   See also
    points2d, minDistancePoints, distancePoints

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SOURCE CODE ^

0001 function [index, minDist] = findClosestPoint(coord, points)
0002 %FINDCLOSESTPOINT Find index of closest point in an array.
0003 %
0004 %   INDEX = findClosestPoint(POINT, POINTARRAY)
0005 %
0006 %   [INDEX, MINDIST] = findClosestPoint(POINT, POINTARRAY)
0007 %   Also returns the distance between POINT and closest point in
0008 %   POINTARRAY.
0009 %
0010 %   Example
0011 %     pts = rand(10, 2);
0012 %     findClosestPoint(pts(4, :), pts)
0013 %     ans =
0014 %         4
0015 %
0016 %   See also
0017 %    points2d, minDistancePoints, distancePoints
0018 %
0019  
0020 % ------
0021 % Author: David Legland
0022 % e-mail: david.legland@grignon.inra.fr
0023 % Created: 2015-02-24,    using Matlab 8.4.0.150421 (R2014b)
0024 % Copyright 2015 INRA - Cepia Software Platform.
0025 % number of points
0026 
0027 % number of point in first input to process
0028 np = size(coord, 1);
0029 
0030 % allocate memory for result
0031 index = zeros(np, 1);
0032 minDist = zeros(np, 1);
0033 
0034 for i = 1:np
0035     % compute squared distance between current point and all point in array
0036     dist = sum(bsxfun(@minus, coord(i,:), points) .^ 2, 2);
0037     
0038     % keep index of closest point
0039     [minDist(i), index(i)] = min(dist);
0040 end

Generated on Wed 16-Feb-2022 15:10:47 by m2html © 2003-2019