Actually no: KNNMax is the maximal number of clusters, into which the data can be sorted. Following the conventional nomenclature in multivariate statistics, n is the number of items (say, persons participating in a study), p the number of variables. Thus, problems would occur only if k (actual number of clusters) is larger than KNNmax, but that is prevented by the calling routine. Indeed, KNNmax is a global constant and set to 15, k is set by the calling routine to 2 for the time being.
I have now modified the inner loop as follows:
for j := 1 to p do begin
x := GetMatrixElement(Data, i, j);
write(k:5, ' ', i:5, ' ', j:5, ' ', n:5, ' ', p:5, ' ', nk:5, ' ', Group[i]:5, ' ', x:3:6, ' ', Sums[j]:3:3, ' ');
Sums[j] := Sums[j] + x;
writeln(p:5, ' ', Sums[j]:3:3);
end;
and got the following result:
k i j n p nk Group x Sums[j] p Sums[j]
2 1 1 101 23 0 1 32.000000 0.000 23 32.000
2 1 2 101 23 0 1 -0.307000 0.000 23 -0.307
2 1 3 101 23 0 1 -0.081000 0.000 23 -0.081
2 1 4 101 23 0 1 -0.466000 0.000 23 -0.466
2 1 5 101 23 0 1 1.170000 0.000 23 1.170
2 1 6 101 23 0 1 1.894000 0.000 23 1.894
2 1 7 101 23 0 1 -0.913000 0.000 23 -0.913
2 1 8 101 23 0 1 0.628000 0.000 23 0.628
2 1 9 101 23 0 1 -0.904000 0.000 23 -0.904
2 1 10 101 23 0 1 0.458000 0.000 23 0.458
2 1 11 101 23 0 1 -1.160000 0.000 23 -1.160
2 1 12 101 23 0 1 0.360000 0.000 23 0.360
2 1 13 101 23 0 1 1.507000 0.000 23 1.507
2 1 14 101 23 0 1 -0.505000 0.000 23 -0.505
2 1 15 101 23 0 1 0.454000 0.000 23 0.454
2 1 16 101 23 0 1 0.753000 0.000 6291 0.753
2 1 17 101 6291 27263 1 0.305000 0.000 6291 0.305
2 1 18 60293 6291 27263 1 -0.453000 0.000 6291 0.000
In other words, the guilty line is
, because when j = 16, p is correct before and wrong afterwards.