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

Hi Folks,

Truly appreciate if any expert can give me some advise to reverese the order of matrix output from Math:;MatrixReal variable.

use Text::CSV; use Math::MatrixReal; my $mref = [ [ 'a', 'b', 'c', 'd', 'e' ], ]; my $matrix = Math::MatrixReal->new_from_rows( $mref ); print $matrix; # this will print [ 'a', 'b', 'c', 'd', 'e' ] # I want to reverse the order inside the matrix which I need later on +to do some more operations. Appreciate the help. #Result: I want the result to be printed like below # print $matrix = [ 'e', 'd', 'c', 'b', 'a' ]

Replies are listed 'Best First'.
Re: Reverse the order of matrix printing using Math::MatrixReal
by kennethk (Abbot) on May 16, 2014 at 15:35 UTC
    From Math::MatrixReal:
    $matrix->swap_col( $col1, $col2 ); This method takes two one-based column numbers and swaps the values of each element in each column. $matrix->swap_col(2,3) would replace column 2 in $matrix with column 3, and replace column 3 with column 2.
    So presumably you would get your desired result with (untested):
    use Text::CSV; use Math::MatrixReal; my $mref = [ [ 'a', 'b', 'c', 'd', 'e' ], ]; my $matrix = Math::MatrixReal->new_from_rows( $mref ); print $matrix; # this will print [ 'a', 'b', 'c', 'd', 'e' ] # I want to reverse the order inside the matrix which I need later on +to do some more operations. Appreciate the help. $matrix->swap_col(1,5); $matrix->swap_col(2,4); #Result: I want the result to be printed like below # print $matrix = [ 'e', 'd', 'c', 'b', 'a' ]
    There's also a swap_row method, depending on what you mean by 'reverese the order of matrix output'.

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Re: Reverse the order of matrix printing using Math::MatrixReal
by AppleFritter (Vicar) on May 17, 2014 at 09:18 UTC

    Expanding on kennethk's reply, here's a snippet showing how to reverse the order of columns in a matrix of arbitrary size:

    #!/usr/bin/perl use Math::MatrixReal; use strict; my $mref = [ [ 1, 2, 3, 4, 5, 6 ], ]; my $matrix = Math::MatrixReal->new_from_rows($mref); my ($rows, $cols) = $matrix->dim(); for(my $currentcol = 1; $currentcol <= $cols / 2; $currentcol++) { $matrix->swap_col($currentcol, $cols - $currentcol + 1); }

    I'm sure there's other (better) ways of doing this, but this works.