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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.