slice#
$pdl->slice($spec) – extract a rectangular slice of an ndarray.
slice is the main dimension-manipulation primitive in PDL.
The spec argument describes, axis by axis, which elements of
$pdl to keep. The resulting child PDL is connected to its
parent by dataflow: it normally does not copy storage, and
writes into the child propagate back into the parent.
Signature#
$child = slice($parent, $spec); # function form
$child = $parent->slice($spec); # method form
$child = $parent->slice("1:3", "*2"); # one string per dim
Slice spec syntax#
Per-axis specifiers, comma-separated if packed into a single string:
Spec |
Meaning |
|---|---|
|
keep axis as-is |
|
a single index (keeps the axis, length 1) |
|
a single index, squish (axis removed) |
|
inclusive range |
|
range with stride |
|
count from the end: |
|
insert a dummy (broadcast) axis of size |
Fewer specs than $parent->ndims leaves the trailing axes intact.
Broadcasting#
slice itself does not broadcast – it structurally rewrites
axes. The *n spec creates a new broadcast axis of size n
with stride 0, i.e. a cheap virtual repeat useful as an input
to later broadcasting ops.
Bad values#
BADFLAG and bad-value storage are preserved from the parent: a
slice of a BAD-flagged PDL is itself BAD-flagged, and the bad
sentinel value is inherited. No bad-specific checks happen
inside slice.
Examples#
use PDL;
my $x = sequence(10); # [0 1 2 3 4 5 6 7 8 9]
print $x->slice("2:5"); # [2 3 4 5]
print $x->slice("0:-1:2"); # [0 2 4 6 8] (stride 2)
print $x->slice("-1:0"); # [9 8 7 6 5 4 3 2 1 0] reversed
my $m = sequence(4, 3); # 4 cols, 3 rows
print $m->slice(":,1"); # row 1: [4 5 6 7]
print $m->slice("(2),:"); # col 2, axis squished: [2 6 10]
## Dataflow: writes propagate
my $row = $m->slice(":,1");
$row .= -1;
print $m; # row 1 of $m is now all -1
## Dummy dim for broadcasting a row-vector against a matrix
my $v = pdl([10, 20, 30, 40]);
my $mat = $v->slice(":,*3"); # 4x3 view, each row equal to $v
Errors#
Croaks with:
"slice: cannot slice a null PDL"when$parenthasPDL_NOMYDIMSset."PDL::slice: slice index 'a:b' out of bounds for dim N of size M"when an index, after negative-index resolution, does not land in[0, dim_size)(test180-slicing-full.t #11).whatever
parse_slice_specreports for malformed spec strings.
Upstream#
Mirrors PDL::Slices::slice in lib/PDL/Slices.pm (generated
from lib/PDL/Slices.pd), which calls the XS pdl_slice_args_parse
helper from pdlutil.c. Parsing happens connector-side in
parse_slice_spec; the engine is invoked for the actual view
construction.