in reply to Nearest Neighbour Analysis subroutine
Two things I should point out: first, your lead comment suggests that the routine be called with a reference to @Matrix, but the routine itself never uses any arguments -- instead it uses the global (or perhaps the file scoped lexical) array of the same name.
More problematic than that is that you've used the ^ where you really wanted to use ** operator (assuming your distance is meant to be standard Euclidean distance: square root of sum of squared differences). Here's a quick rewrite (which also does not require some arbitrary large number to initialize the nearest neighbor distance):
sub nneighbours { die "Bad Input Matrix: must be even" if @_ % 2; my @mat = @_; my $sum = 0; my $limit = $#mat; for(my $i = 0; $i < $limit; $i += 2){ my $nearest; for(my $j = 0; $j < $limit; $j += 2){ next if $i == $j; my $dist = sqrt(($mat[$i] - $mat[$j]) ** 2 + ($mat[$i+1] - $mat[$j+1]) ** 2); $nearest = defined $nearest? ($nearest > $dist ? $dist : $nearest) : $dist; } $sum += $nearest; } return $sum; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Nearest Neighbour Analysis subroutine
by Elias (Pilgrim) on Jan 15, 2001 at 22:02 UTC | |
by danger (Priest) on Jan 15, 2001 at 22:12 UTC | |
by merlyn (Sage) on Jan 15, 2001 at 22:09 UTC |