Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Slice of a multidimensional array

by BrowserUk (Patriarch)
on Mar 06, 2003 at 18:04 UTC ( [id://240954]=note: print w/replies, xml ) Need Help??


in reply to Slice of a multidimensional array

There are two way of looking at what constitutes a slice of a 2d array--and more for higher dimensions:)

In the first veiw, the result is what you would get if you could notionally extend perl's @arr[n..m] syntax to a 2D array: @arr[*][n..m] which might be described as "Give me a new 2d array where each row consists of just the columns n through m of the original array". For your example array, and with n & m set to 1 & 2 respectively, this would result in

my @vslice = (['b','c'], ['i','j'], ['y','z']);

The second view, and the one you want, is where the resultant arrays row(s) become 1 (or more) column(s) from the original array. for the same example as above you get

my @yxslice = ( ['b','i','y'], ['c','j','z'] );

Two functions to produce these

#! perl -slw use strict; use Data::Dumper; sub vslice { map{ [ @{$_}[@_] ] } @{+shift}; } sub yxslice { my $aref = shift; map{ my $i=$_; [ map{ $_->[$i] } @$aref ] } @_; } my @arr = (['a','b','c','d'], ['h','i','j','k'], ['w','x','y','z']); my @vslice = vslice \@arr, 1..2; print Dumper \@vslice; my @yxslice = yxslice \@arr, 1..2; print Dumper \@yxslice; __END__ C:\test>240941 $VAR1 = [ [ 'b', 'c' ], [ 'i', 'j' ], [ 'x', 'y' ] ]; $VAR1 = [ [ 'b', 'i', 'x' ], [ 'c', 'j', 'y' ] ];

I would use these versions of the two functions as it simplifies the syntax of using them slightly, but prototypes are almost universally condemned.

sub vslice (\@@) { map{ [@{$_}[@_]] } @{+shift}; } sub yxslice (\@@) { my $aref = shift; map{ my $i=$_; [ map{ $_->[$i] } @$aref ] } @_; }

Examine what is said, not who speaks.
1) When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
2) The only way of discovering the limits of the possible is to venture a little way past them into the impossible
3) Any sufficiently advanced technology is indistinguishable from magic.
Arthur C. Clarke.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2024-04-25 21:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found