# Function inside for loop that calls multi-column variables

2 ビュー (過去 30 日間)
Tricia 2019 年 11 月 8 日
Commented: dpb 2019 年 11 月 12 日
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)
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));
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.

#### 0 件のコメント

サインイン to comment.

### 採用された回答

dpb 2019 年 11 月 9 日
Vectorize the function instead..."the MATLAB way"
function [d1km]=latlondist(LL1,LL2)
dLL=LL2-LL1;
a=sin(dLL(:,1)/2).^2 + cos(LL1(:,1)).*cos(LL2(:,2)).*sin(dLL(:,2)/2)^2;
end

#### 2 件のコメント

Tricia 2019 年 11 月 11 日
function [dkm_fwbrev]=latlondist(LL1,LL6)
dLL=LL6-LL1;
a=sin(dLL(:,2)/2).^2 + cos(LL1(:,2)).*cos(LL6(:,2)).*sin(dLL(:,1)/2).^2;
end
Thank you for your help! The problem is solved. I had to add a "." after the last sin function and switch which columns were used in the calculation given how my variables were structured. In the end, this is the function that ended up working for me and I was able to call it with
[dkm_fwbrev]=latlondist(LL1,LL6)
dpb 2019 年 11 月 12 日
Yeah, I missed the second exponentiation .^.
NB: You do NOT need the arguments in the function to reflect the calling variable names -- in fact, I'd strongly recommend against doing so but using the 1,2 suffixes instead to be more generic of the two as you had before.
The arguments in the function definiton are dummy arguments; they are placeholders for the actual arguments when the function is called; nothing more. There is no association outside that link.

サインイン to comment.