3

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?

marcantonio
  • 958
  • 10
  • 24

2 Answers2

3

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]
]
Borodin
  • 126,100
  • 9
  • 70
  • 144
  • Thanks! It looks like I can use multiple conditions with something like `$aa->dice_axis(1, which($aa->index(0) == 1 & $aa->index(2) == 1))`. Is that correct? – marcantonio Aug 17 '18 at 01:57
  • @marcantonio: Pretty much yes. But `&` in Perl is a bitwise mask operator; you need `&&` or `and`, which are identical but with different precedences. – Borodin Aug 17 '18 at 02:57
  • 1
    I came across this: http://pdl.perl.org/?docs=FAQ&title=PDL::FAQ%20-%20Frequently%20Asked%20Questions#Q:-6.11-Logical-operators-and-piddles---and-dont-work which is why I used `&` rather than `&&`. – marcantonio Aug 17 '18 at 18:02
1

I'm new to PDL, but it seems like you can use which result as a mask.

You need to transpose original variable first, then transpose it back after using slice.

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

pdl> p which($a(2) == 1)
[0 2]

pdl> p $a->transpose    

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

pdl> p $a->transpose->slice(which($a(2) == 1))->transpose

[
 [1 0 1]
 [0 1 1]
]
ernix
  • 3,442
  • 1
  • 17
  • 23
  • 3
    Note that this won't work in a Perl program without the addition of `use PDL::NiceSlice`. This module allows more concise `slice`/`dice` expressions, but it uses source filtering, which is generally a Bad Thing. – Borodin Aug 16 '18 at 01:22