David92 has asked for the wisdom of the Perl Monks concerning the following question:

Hey friends,

I have created a matrix with array in an array method:

@myMatrix = ( [$value1,$value2,$value3], [$value4,$value5,$value6]);

I'd like to get this Matrix's size. With:

$matrixSize = @myMatrix;

I get a values of 3 - which means he counts only the first row. So if anyone knows how to get the matrix size would be awesome!

Please, let the answer be general - my matrix changes depending on how many variables will be in my Hash. So do not just focus on this example, I need something like "getMatrixsize" function. :)

Wish you all a great day, David

Replies are listed 'Best First'.
Re: How to get Matrix Size
by hippo (Archbishop) on Jul 18, 2014 at 09:36 UTC
    I get a values of 3

    How do you do that? You should get a value of 2. viz:

    $ cat mat.pl #!/usr/bin/perl -w use strict; use warnings; my $value1 = 1; my $value2 = 1; my $value3 = 1; my $value4 = 1; my $value5 = 1; my $value6 = 1; my @myMatrix = ( [$value1,$value2,$value3], [$value4,$value5,$value6]); my $matrixSize = @myMatrix; print $matrixSize . "\n"; $ perl mat.pl 2 $
Re: How to get Matrix Size
by AppleFritter (Vicar) on Jul 18, 2014 at 09:46 UTC

    Howdy David, welcome back to the Monastery!

    I'm a little surprised that you're getting a value of 3 by evaluating @myMatrix in a scalar context; it should be 2, since @myMatrix is a list with two elements (which just so happen to be array references).

    You can get the number of rows and columns in your matrix like this:

    $rows = @myMatrix; $cols = @{ $myMatrix[0] };

    That said, I'd suggest using an existing module for working with matrices instead of rolling your own, unless there's a compelling reason not to. A quick CPAN search finds e.g. Math::GSL::Matrix and Math::Matrix.

Re: How to get Matrix Size
by Anonymous Monk on Jul 18, 2014 at 08:52 UTC

    Where did you learn to create a matrix? It should also discuss access

    my $rows = @myMatrix; my $cols = @{ $myMatrix[0] };
    Modern Perl by chromatic a loose description of how experienced and effective Perl 5 programmers work....You can learn this too.

    It is reviewed and recommended by Perl Tutorial Hub

Re: How to get Matrix Size
by David92 (Sexton) on Jul 18, 2014 at 09:51 UTC
    Sorry for the confusion guys, I had a typo up there! it is indeed 2 the matrix size in my case.

    Thanks for the answers. They did what I wanted to do!