This subroutine is for the benefit of any plant ecologists wandering through this monastery. It will calculate the sum of nearest neighbours of samples which are each in discrete sampling points. The coordinates of these points should be put in the @Matrix as qw(x y x y x y etc.). The distance from each sample to all other samples will be calculated, and from this list the shortest one is extracted and added to the sum, which will contain as many elements as there are samples. I use it in conjunction with the Fisher-Yates shuffle from the Perl Cookbook to test the significance of the results with a permutation test.
I submit the subroutine below with some trepidation, since I know it is substandard in many respects, but the me of a few months ago really wanted it to be here (before I was able to do this by myself).
sub NearestNeighbours { #call as NearestNeighbours(\@Matrix) $sumNN=0; #initialize sum my $numberofsamples=scalar(@Matrix)/2; my $counter_outer=$numberofsamples; my $counter_inner=$numberofsamples; my ($xDNM, $yDNM, $xMoves, $yMoves,$i,$j); OUTER: for ($i = 1; $i <= $counter_outer; $i++) { my $NearestNeighbour=1000000;#initialize to something +insanely large my $distance = 0; #initialize distance my $c=(2*$i-1); $xDNM=@Matrix[$c-1]; #xDoesNotMove $yDNM=@Matrix[$c]; INNER: for ($j = 1; $j <= $counter_inner; $j++) { my $d=(2*$j-1); if ($c==$d) {next INNER} $xMoves=@Matrix[$d-1]; $yMoves=@Matrix[$d]; $distance = sqrt(($xDNM-$xMoves)^2+($yDNM-$yMoves +)^2); if ($distance<$NearestNeighbour) {$NearestNeighbo +ur=$distance} } # next comparison for this sample $sumNN=$sumNN+$NearestNeighbour; } #next sample return ($sumNN); }# end of sub.
In reply to Nearest Neighbour Analysis subroutine by Elias
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |