http://qs321.pair.com?node_id=86482

eyal_kle has asked for the wisdom of the Perl Monks concerning the following question: (arrays)

How do I create a matrix? is it @@matrix?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I create a matrix?
by jeffa (Bishop) on Jun 07, 2001 at 12:07 UTC
    Heh, close. :)
    The trick is to use an array of array references:
    my @matrix = ( [qw(0 0 0 0)], [qw(0 0 1 0)], [qw(0 1 0 0)], [qw(1 0 0 0)], ); foreach my $row (@matrix) { print join(":",@$row), "\n"; } # qw(1 0 0 0) is better way of saying (1,0,0,0)
Re: How do I create a matrix?
by Beatnik (Parson) on Jun 07, 2001 at 12:33 UTC
    You can use PDL::Matrix
    #!/usr/bin/perl -w use strict; use PDL::Matrix; my $m = pdl [ [1,2,3], [4,5,6], [7,8,9] ];
    Which then also allows you to perform clean, fast math on them.
    my $m = pdl [ [1,2,3], [4,5,6], [7,8,9] ]; my $n = pdl [ [1,0,0], [0,1,0], [0,0,1] ]; my $r = $m x $n;
      The above appears not to use PDL::Matrix-specific features (which are full of gotchas); better practice would be just to use PDL, and all the rest of the code above will then work as given. Try perldl after installing PDL, the online help is really good. For better matrix support, try also PDL::LinearAlgebra.