function len = path_length ( p, D )

%*****************************************************************************80
%
%% path_length() computes the current path length.
%
%  Discussion:
%
%    This function calculates the total length of the current path p
%    in the traveling salesman problem, using a distance matrix D.
%
%    This is a vectorized distance calculation.
%
%  Licensing:
%
%    Copyright 1984-2018 The MathWorks, Inc.
%
%  Modified:
%
%    13 March 2023
%
%  Author:
%
%    Cleve Moler
%    Modifications by John Burkardt
%
%  Reference:
%
%    Cleve Moler,
%    USA Traveling Salesman Tour,
%    Posted 17 September 2018,
%    logs.mathworks.com/cleve/2018/09/17/usa-traveling-salesman-tour/?s_tid=srchtitle_traveling%20salesman_1
%
%  Usage:
%
%    len = path_length ( p, D )
%
%  Input:
%
%    integer p(n): the sequence of cities in the current path.
%
%    real D(n,n): the city-to-city distance matrix.
%
%  Output:
%
%    real len: the current length of the path.
%
%  Local:
%
%    integer q(n): the pair ( p(i), q(i) ) describes the i-th leg of the path.
%   
  n = length ( p );
  q = p( [ n, 1:(n-1) ] );
%
%  Use column indexing into D to create a vector of
%  lengths of each leg which can then be summed.
%
  len = sum ( D(q + (p-1)*n));

  return
end
