MATLAB: Finding values based on coordinates

closestcoordinatesMATLAB

I have two different matrices, the first is a set of decimal coordinates with a value for the carbon density of the soil at those coordinates which is set out as [long, lat, value]. The second is a set of coordinates with land displacement values at the coordinates set out as [long, lat, displacement].
The first matrix has a very large number of points and the second one covers a much smaller section of the first one. I need to create a scrip which takes the coordinates from the second matrix and finds the closest coordinates in the first matrix and then appends the value to a 4th column of the second matrix.
I have to use the closest coordinate as the coordinates of the first matrix are not exactly the same as the coordinates of the second matrix. I have no idea where to start with this, any help or advice will be greatly appreciated.

Best Answer

If you have the Statistics Toolbox, take a look at knnsearch. Depending on the geographic extent of your coordinates, you may need to input a custom distance function to calculate geographic distance instead of cartesian, e.g
dis = @(ltlni, ltlnj) distance(ltlni(:,2), ltlni(:,1), ...
ltlnj(:,2), ltlnj(:,1), ...
referenceEllipsoid('earth'));
[idx, d] = knnsearch(soil(:,1:2), landdis(:,1:2), 'distance', dis);
(That example will require the Mapping Toolbox for distance).