in reply to Remove row if the absolute difference between two columns is greater than a threshold

Here's a short script that I think does what you're after. I didn't spend any time optimizing it; so it is just so you can see a quick and dirty strategy.

It uses Perl references to create 2 dimensional matrices and the arrow notation to simplify and clarify what is going on. The subrouting, printMatrix(), is just for convenience so that you can better see what the 'before' and 'after' situation looks like.

#!/usr/bin/perl use strict; use warnings; $| = 1; # set print buffering to not buffe print "OLD MATRIX:\n"; my $matrix = [ [ 4, 3, 2, 1], [ 1, 2, 1, 1], [ 4, 1, 3, 4], [ 5, 6, 5, 4] ]; printMatrix($matrix); my $nRows = scalar(@{$matrix}); my $nCols = scalar(@{$matrix->[0]}); my $newMatrix = []; print "\n"; foreach my $row (0..($nRows-1)){ my $doIt = 1; foreach my $col (1..($nCols-1)){ if(abs($matrix->[$row][($col-1)] - $matrix->[$row][$col])>1){ $doIt = 0; print "*** DROPPING ROW $row ***\n"; last; } } push(@{$newMatrix},$matrix->[$row]) if($doIt); } print "\n"; print "NEW MATRIX:\n"; printMatrix($newMatrix); exit(0); sub printMatrix { my($matrix) = @_; my $nRows = scalar(@{$matrix}); return 0 if($nRows==0); my $nCols = scalar(@{$matrix->[0]}); return 0 if($nCols==0); foreach my $row (0..($nRows-1)){ print " ROW $row: "; foreach my $col (0..($nCols-1)){ printf "%3d ",$matrix->[$row][$col]; } print "\n"; } return 1; }

The output from the little script is:

OLD MATRIX: ROW 0: 4 3 2 1 ROW 1: 1 2 1 1 ROW 2: 4 1 3 4 ROW 3: 5 6 5 4 *** DROPPING ROW 2 *** NEW MATRIX: ROW 0: 4 3 2 1 ROW 1: 1 2 1 1 ROW 2: 5 6 5 4

Good luck; welcome to Perl.

ack Albuquerque, NM
  • Comment on Re: Remove row if the absolute difference between two columns is greater than a threshold
  • Select or Download Code