Jan 18, 2010

PHP: calculate distance between two points

Each point is an one-dimensional array, each value in the array is a coordinate, so dimension of coordinates in this function is arbitriary.
 /*
 * Calculates Euclidian distance between two points in p-norm
 * Points $p1 and $p2 are Nx1 matrices
 */
 function euclidian_distance($p1,$p2) {
  if(count($p1) != count($p2)) return false;
  $distances = 0;
  
  $p1 = array_values($p1);
  $p2 = array_values($p2);
  
  $norm = count($p2);
  
  for($i=0;$i<$norm;$i++) $distances += pow(abs($p1[$i]-$p2[$i]),2);
  
  return pow($distances,1/2);
 }

No comments: