Presuming your first data set is in a matrix X, where the first column is latitude and the second is longitude and any other columns are existing data:
xlat = floor(X(1,:));
xlon = floor(X(2,:));
lat = % a list of the latitudes covered in the grid
lon = % a list of the longitudes covered in the grid
data = % the matrix of data you want to extract - a 2D grid
Such that lat(n),lon(m)
together forms a reference to the left-bottom corner of the grid square, which contains data in data(n,m)
. floor
rounds down, so that anything between 100 and 101 will be linked to 100, etc.
Now:
[~ n] = ismember(xlat,lat);
[~ m] = ismember(xlon, lon);
n
and m
are not latitudes or longitudes but indexes which relate the points in your data set X
to some values in lat
and lon
which then refer to some value in the grid data
.
Here's the last trick - use sub2ind
to convert your n
and m
references to a single reference to the position in the grid, then extract all the required data in one go:
ind = sub2ind(size(data),n,m); % presuming the size of data is lat x lon);
Xdata = data(ind);
Xdata
should be a single column, with the same size as the number of rows in X
.