Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Remove row if the absolute difference between two columns is greater than a threshold

by ack (Deacon)
on Feb 15, 2011 at 17:48 UTC ( [id://888327]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://888327]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (7)
As of 2024-04-23 12:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found