I am implementing k- nearest neighbor alog using euclidian distance formula for 2-D data in my sql table. Things look ok below even it shows strange behavious.
Code:
$result1 = mysqli_query($con,"SELECT pcount, ncount from test");
$result2 = mysqli_query($con,"SELECT pcount, ncount from test");
$i = 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;
while ($row2 = @mysqli_fetch_array($result2))
{
echo "j is $j <br/>";
$a[$j] = $row2['pcount'];
$b[$j] = $row2['ncount'];
$diff = sqrt(($a[$i] - $a[$j])^2 + ($b[$i] - $b[$j])^2 );
$j= $j + 1;
echo "$diff <br>";
}
echo "i is $i <br/>";
$i = $i + 1;
}
it gives this result:
j is 0
Difference : 0
j is 1
Difference : 1.4142135623731
j is 2
Difference : 0
j is 3
Difference : 0
j is 4
Difference : 1.4142135623731
j is 5
Difference : 1.4142135623731
j is 6
Difference : 1.4142135623731
i is 0
In table I have total 8 rows, but above result is for 7 rows only. Why?
And First while loop gets executed for $i = 0 on, for rest i=1 to 7 no operation. Can some one tell me what is bug?
data in table is
pcount ncount
20 80
21 79
20 80
21 79
19 81
20 80
20 80
20 80
result after fallens answer:
j is 0
Difference : 0
j is 1
Difference : NAN
j is 2
Difference : 0
j is 3
Difference : NAN
j is 4
Difference : 1.4142135623731
j is 5
Difference : 0
j is 6
Difference : 0
j is 7
Difference : 0
i is 0
pcount is 21
ncount is 79
i is 1
pcount is 20
ncount is 80
i is 2
pcount is 21
ncount is 79
i is 3
pcount is 19
ncount is 81
i is 4
pcount is 20
ncount is 80
i is 5
pcount is 20
ncount is 80
i is 6
pcount is 20
ncount is 80
i is 7