Alex Rivera | Logout

Matrices of Matrices within Perl

Asked 2009-03-03T22:02:44.280
9

In a Perl script I'm working on, I need to build a matrix out of several other matrices. I've looked at a couple of modules in CPAN (Math::Matrix, PDL::Matrix, Math::Cephes::Matrix), but none of these seem to support this.

In Octave, this is very easy. Here's an example of something similar to what I'm trying to do:

octave:1> A = [ 1, 2; 3, 4 ]
A =    
   1   2
   3   4

octave:2> B = [ 5, 6; 7, 8 ]
B =    
   5   6
   7   8

octave:3> C = [ 9, 10; 11, 12 ]
C =    
    9   10
   11   12

octave:4> D = [ 13, 14; 15, 16 ]
D =    
   13   14
   15   16

octave:5> E = [ A, B; C, D ]
E =    
    1    2    5    6
    3    4    7    8
    9   10   13   14
   11   12   15   16

It seems trying to do this myself would get messy kinda quickly, which is probably why these modules don't support it... Has anyone else out there ever had a need for this? Have you solved it?

Edit
Report

1 Answer

0

The Perl Data Language (PDL) version 2.4.10 supports MATLAB-style convenience input for the pdl constructor when using a string argument and the append and glue routines can be used to paste subarrays together as this pdl2 session shows:

pdl> $A = pdl q[ 1, 2 ; 3, 4 ];       # pdl constructor with string argument

pdl> $B = pdl q[ 5, 6 ; 7, 8 ];       # pdl constructor with string argument

pdl> $C = pdl q[ 9, 10 ; 11, 12 ];    # pdl constructor with string argument

pdl> $D = pdl q[ 13, 14 ; 15, 16];    # pdl constructor with string argument

pdl> ?vars
PDL variables in package main::

Name         Type   Dimension       Flow  State          Mem
----------------------------------------------------------------
$A           Double D [2,2]                P            0.03KB 
$B           Double D [2,2]                P            0.03KB 
$C           Double D [2,2]                P            0.03KB 
$D           Double D [2,2]                P            0.03KB 


pdl> p $A, $B, $C, $D;

[
 [1 2]
 [3 4]
]

[
 [5 6]
 [7 8]
]

[
 [ 9 10]
 [11 12]
]

[
 [13 14]
 [15 16]
]

pdl> p $AB = $A->append($B);          # concatenate horizontally (actually on dim(0))

[
 [1 2 5 6]
 [3 4 7 8]
]

pdl> p $CD = $C->append($D);          # concatenate horizontally (actually on dim(0))

[
 [ 9 10 13 14]
 [11 12 15 16]
]

pdl> p $E = $AB->glue(1,$CD);         # glue vertically (actually on dim(1))
[
 [ 1  2  5  6]
 [ 3  4  7  8]
 [ 9 10 13 14]
 [11 12 15 16]
]

The PDL book and the PDL mailing lists are essential sources for more information on PDL.

answered 2012-04-24T20:01:56.610

Your Answer