0
votes

In the past, in MATLAB, I've calculated the index of a point given its lat and lon using a great circle distance calculation. I'll share my code with you. I'm fairly stumped as to what the equivalent function in R would look like or whether on exists? I've found some code that shows the distance between two points, but none that help me to index my data.

This is my MATLAB code!

%% Define latlon grid and coordinates (lon follows lat) 

lon_grid = transpose([40.1 40.12 40.14; 40.3 40.32 40.34; 40.5 40.52 40.54]);
lat_grid = transpose([30 30.2 30.4;30.02 30.22 30.42; 30.04 30.24 30.44]);
coord = [30.4125 40.4043];

%% Compute great circle distance
dist = distance('gc',coord(1),coord(2),lat_grid,lon_grid);

%% Retrieve index of minimum distance
[value,array_index] = min(distance(:));
[i,j] = ind2sub(size(dist),array_index);

The "dist" calculation is sort of the party piece here. You should be able to use the provided code to reproduce the results and see what I'm hoping to achieve in R.

Again, what might a comparable function in R be given I have the following: A grid of latitude points A grid of longitude points Two points, in degrees, for the latitude and longitude of my position.

1
You can always just take the Haversine formula and convert it to R code. Are you looking for a package which already does this?Tim Biegeleisen
I was hoping to find one, but worst case scenario I'll tackle the problem that way!Taylor
Searching Stack Overflow's R tag for "great circle distance" gives quite a few results with sample code. Did you try any of those and get stuck?Gregor Thomas

1 Answers

1
votes

maybe this works:

library(geoshpere)

dist<-apply(coord, 1, FUN=function(p) distHaversine(p, lonlat_matrix))