- or download this
my $A = [ [ 1, 2 ],
[ 3, 4 ] ]; # matrix A
...
[ 7, 8 ] ]; # matrix B
my $mats = [ $A, $B ]; # array of matrices
- or download this
# [ [ f(1,5), f(2,6) ],
# [ f(3,7), f(4,8) ] ]
- or download this
# c=0 c=1
# ________
...
# /___/___/
#
# c=0 c=1
- or download this
my $result;
for my $r (0 .. @{$mats->[0]} - 1) {
...
$result->[$r][$c] = f( map $_->[$r][$c], @$mats );
}
}
- or download this
use Data::Dumper;
...
tr/\'//d;
$_;
}
- or download this
print dumpf($result), $/;
# [ [f(1,5), f(2,6)],
# [f(3,7), f(4,8)] ]
- or download this
sub mapat {
my $depth = shift;
...
? map [ map mapat($depth-1, $f, $_), @$_ ], @_
: $f->(@_);
}
- or download this
for (0..3) {
print "mapat $_ f: ",
...
# mapat 1 f: [f([[1,2],[3,4]]),f([[5,6],[7,8]])]
# mapat 2 f: [[f([1,2]),f([3,4])],[f([5,6]),f([7,8])]]
# mapat 3 f: [[[f(1),f(2)],[f(3),f(4)]],[[f(5),f(6)],[f(7),f(8)]]]
- or download this
# Dimensions
#
...
# [ 3, 4 ], <=== transpose ===> [ 2, 4, 6 ] ]
# [ 5, 6 ] ]
#
- or download this
sub zip {
my $len = min( map scalar @$_, @_ );
...
sub transpose {
map [ zip(@$_) ], @_;
}
- or download this
# 0 1 2 0 1 2
# (m,r,c) -> (r,m,c) # via transpose(...)
#
# ([[[1,2],[3,4]],[[5,6],[7,8]]]
# -> [[[1,2],[5,6]],[[3,4],[7,8]]]
- or download this
# 0 1 2 0 1 2
# (r,m,c) -> (r,c,m) # via mapat(1, \&transpose, ...)
#
# [[[1,2],[5,6]],[[3,4],[7,8]]]
# -> [[[1,5],[2,6]],[[3,7],[4,8]]]
- or download this
mapat(2, \&f, [[[1,5],[2,6]],[[3,7],[4,8]]]);
# [[f([1,5]),f([2,6])],[f([3,7]),f([4,8])]]
- or download this
sub matrixwise_map(&@) {
my $f = shift;
# force array context since we're always dealing w/ matricies
( mapat( 2, $f, mapat(1, \&transpose, transpose(@_)) ) )[0];
}
- or download this
$result = matrixwise_map(\&f, $mats);
print dumpf($result), $/;
# [[f([1,5]),f([2,6])],[f([3,7]),f([4,8])]]
- or download this
use List::Util qw( sum );
sub mean { sum(@_) / @_ }
print dumpf( matrixwise_map {mean(@$_)} $mats ), $/;
# [[3,4],[5,6]]