MATLAB: Function inside for loop that calls multi-column variables

forfor loopmultiple columnsmultiple variables

Hi all,
I am trying to call a function that will take two sets of lat lon coordinates and calcuate the distance between them in km. The function latlondist.m itself works for single sets of coordinates, but I am having trouble getting this function to perform iteratively. I have two sets of variables that are used by the function latlondist.m that are both two column doubles, latlon1 and latlon6. I would like my for loop output to be one column containing the distances between the lat lon coordinates in their corresponding rows. For example, for the first row of latlon1 and latlon6 I would like it to execute the function and put the result in the first row of dkm_fwbrev then proceed to second row of both latlon1 and latlon6 and put the output in the second row of dkm_fwbrev, and so on.
Here is the function:
function [d1km]=latlondist(latlon1,latlon2)
radius=6371;
lat1=latlon1(1)*pi/180;
lat2=latlon2(1)*pi/180;
lon1=latlon1(2)*pi/180;
lon2=latlon2(2)*pi/180;
deltaLat=lat2-lat1;
deltaLon=lon2-lon1;
a=sin((deltaLat)/2)^2 + cos(lat1)*cos(lat2) * sin(deltaLon/2)^2;
c=2*atan2(sqrt(a),sqrt(1-a));
d1km=radius*c; %Haversine distance
end
Here is what I have so far:
%define input variables for latlondist.m function
if eventID_1 == eventID_6
latlon1 = [lon_1 lat_1];
latlon6 = [lon_6 lat_6];
end
dkm_fwbrev = zeros(length(lon_1),1);
for index_fwbrev = 1:length(dkm_fwbrev)
[dkm_fwbrev]=latlondist(latlon1(:,index_fwbrev),latlon6(:,index_fwbrev));
end
The error that this returns is Index exceeds matrix dimensions. Any help would be appreciated.

Best Answer

Vectorize the function instead..."the MATLAB way"
function [d1km]=latlondist(LL1,LL2)
RADIUS=6371;
LL1=deg2rad(LL1);
LL2=deg2rad(LL2);
dLL=LL2-LL1;
a=sin(dLL(:,1)/2).^2 + cos(LL1(:,1)).*cos(LL2(:,2)).*sin(dLL(:,2)/2)^2;
d1km=2*RADIUS*atan2(sqrt(a),sqrt(1-a));
end