function M = shared_bd_lengths(DAT);

% SHARED_BD_LENGTHS takes a list of shared boundary lengths from ARCMAP
% and reduces it to those boundaries shared by distinct polygons, and creates a 
% matrix of shared boundary lengths. 

%Written by: TONY E. SMITH 4/16/06 (with many thanks to DANA TOMLIN)

%NOTE_1: ARCMAP sometimes stores shared boundaries in more than one piece.
%So this procedure proceeds by finding for each pair of polygons (i < j) all 
%instances of this pair, and adding their lengths together

%NOTE_2: If a polygon is an island it will have a zero row.

%INPUT:  DAT = Nx3 matrix with rows (i,j,length_ij)

n = max(DAT(:,1)); %number of polygons

M = sparse(n,n); %nxn sparse zero matrix

N = size(DAT,1);

for ctr = 1:N
    
    i = DAT(ctr,1);
    
    j = DAT(ctr,2);
    
    if i < j %Selects only distinct ordered pairs
        
        M(i,j) = M(i,j) + DAT(ctr,3); %cumulates lengths
        
        M(j,i) = M(i,j); %Fills other half of M
        
    end
    
end


    
    

    
    


