Question

I have two co-ordinate values. And I am calculatting euclidian distance for each co-ordinate. I want to apply K- nearest neighborhood algo here.

  1. For each co-ordinate get euclidian distance with all other points
  2. Select the point which is nearest to maximum points (from all points, select that point which appears as nearest for maximum numbers of co-ordinates)

        $result2 = mysqli_query($con,"SELECT pcount, ncount from test");
        $result1 = mysqli_query($con,"SELECT pcount, ncount from test");
        $i = 0;
                    $k = 0;
        $min = 0;
        while ($row1 = @mysqli_fetch_array($result1))
        {
            $pcount = $row1['pcount'];
            $ncount = $row1['ncount'];
            echo "pcount is $pcount<br/>";
            echo "ncount is $ncount<br/></br>";
            $a[$i] = $pcount ;
            $b[$i] = $pcount ;
            $j = 0;
            $result2 = mysqli_query($con,"SELECT pcount, ncount from test");
            while ($row2 = @mysqli_fetch_array($result2))
            {
            //echo "j is $j <br/>";
            $a[$j] = $row2['pcount'];   
            $b[$j] = $row2['ncount'];
            $diff = ($a[$i] - $a[$j])^2 + ($b[$i] - $b[$j])^2;
            if( $diff != 0)
                $diff = sqrt( $diff );
                $j= $j + 1;
                echo "$diff <br>";
                            arr[$k] = $diff;
                            $k = $k + 1;
            }               
            //echo "i is $i <br/>";
                $i = $i + 1;    
        }
    

Here, arr[$k] contains distance difference for all points. How can I get point which is nearest to maximum other points here. There may be more then 1 such points.

Was it helpful?

Solution

I suggest to use the following method.

0) Fetch db data into 2d array looks like this:

array(
    array($x1,$y1),
    array($x2,$y2),
    ...
)

1) Build array storing for each point sum of (square) distances to all other points.

2) Find the lowest value in that array (minimum).

3) Get all points having that value.

So the code should look like this:

// $a_points = array( array($x1,$y1), array($x2,$y2), ... ); // array of point coordinates

$a_sum_dists = array();
foreach ($a_points as $i => $pt1) {
    list($x1, $y1) = $pt1;
    $sum = 0;
    foreach ($a_points as $j => $pt2) {
        if ($j == $i) continue;
        list($x2, $y2) = $pt2;
        $sum += pow($x2- $x1, 2) + pow($y2- $y1, 2);
    }
    $a_sum_dists[$i] = $sum;
}
$min_sum = min($a_sum_dists);
$a_result_points = array_intersect_key(
    $a_points, 
    array_filter($a_sum_dists, function ($v) use ($min_sum) {
        return $v == $min_sum;
    })
);

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top