in reply to Re: How to output matrix data from Math:;MatrixReal into a Hash or an Array
in thread How to output matrix data from Math:;MatrixReal into a Hash or an Array

Folks, Thanks for your answers. When I print a particular matrix I get following Data dumper format. This is a 5 x 5 matrix. I would like to print it to csv file like below.

where each 1,1,1,1,1 is my first column A in csv then B ...

A B C D E 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5

print Dumper $matrix; $VAR1 = bless( [ [ [ '5', '4', '4', '2', '4' ], [ '9', '6', '4', '4', '3' ], [ '2', '73', '96', '6', '8' ], [ '2', '4', '9', '87', '8' ], [ '2', '4', '10', '6', '8' ], ], 5, 5 ], 'Math::MatrixReal' );

Appreciate your help if you can give me the code for this matrix printing to a output file like csv. </code>

Replies are listed 'Best First'.
Re^3: How to output matrix data from Math:;MatrixReal into a Hash or an Array
by davido (Cardinal) on May 13, 2014 at 01:56 UTC

    The documentation for the Math::MatrixReal module discusses the element method, and the row method. Since the row method (inconveniently, in this case) generates a new 1xN matrix object, it's not as useful for file dumps as "element", which just returns plain old values.

    All you really have to do is iterate over the rows, over the columns, and build up a CSV file. I chose to use Text::CSV in this solution, but it's so trivial that it would probably be easier and no less maintainable to just generate your own CSV:

    use Text::CSV; use Math::MatrixReal; my $mref = [ [ '5', '4', '4', '2', '4' ], [ '9', '6', '4', '4', '3' ], [ '2','73','96', '6', '8' ], [ '2', '4', '9','87', '8' ], [ '2', '4','10', '6', '8' ], ]; my $matrix = Math::MatrixReal->new_from_rows( $mref ); # At this point $matrix is a Math::MatrixReal object that # resembles the one you showed us a Data::Dumper dump of. my $csv = Text::CSV->new; foreach my $row_num ( 1 .. 5 ) { $csv->print(*STDOUT, [ map { $matrix->element($row_num,$_) } 1 .. 5 +] ); print {*STDOUT} "\n"; }

    Substitute *STDOUT for your own output file handle, of course.


    Dave

      Hi Dave, shouldn't it use 0..4 rather than 1..5 to index the rows and columns of the matrix?

        It's not documented in the pod, but my own test runs indicated that the elements accessor is 1-based. Maybe that's how mathematics people like their matrices indexed... I dont know. But it seems to be how this module does it. Using zero will throw an out of range error.


        Dave