perlpdl

How do I extract specific rows from a PDL matrix?


Suppose I have:

$a = [
      [1, 0, 1]
      [0, 1, 0]
      [0, 1, 1]
     ]

and I want to extract all rows where $row[2] == 1. My resulting piddle would look like:

$b = [
      [1, 0, 1]
      [0, 1, 1]
     ]

Is this possible with PDL?


Solution

  • You need to use which to generate a list of indexes of your matrix which have a value of 1 in the third column

    which($aa->index(2) == 1)
    

    and pass this to dice_axis, which will select the rows with the given indexes. Axis 0 is the columns and axis 1 is the rows, so the code looks like this

    use strict;
    use warnings 'all';
    
    use PDL;
    
    my $aa = pdl <<__END_PDL__;
    [
      [1, 0, 1]
      [0, 1, 0]
      [0, 1, 1]
    ]
    __END_PDL__
    
    my $result = $aa->dice_axis(1, which($aa->index(2) == 1));
    
    print $result;
    

    output

    [
     [1 0 1]
     [0 1 1]
    ]