etheral has asked for the wisdom of the Perl Monks concerning the following question:
#################################################################### ## MAIN #################################################################### my $x = [ [ 3, 2, 3 ], [ 5, 9, 8 ], ]; my $y = [ [ 4, 7 ], [ 9, 3 ], [ 8, 1 ], ]; my $z = get_multiplied_matrix($x, $y); print "$z\n"; #################################################################### ## SUBS #################################################################### sub get_multiplied_matrix { my ($matrix_1, $matrix_2) = @_; my ($matrix_1_rows, $matrix_1_columns) = matrix_dimension($matrix_1) +; my ($matrix_2_rows, $matrix_2_columns) = matrix_dimension($matrix_2) +; unless ($matrix_1_columns == $matrix_2_rows) { die "Matrices don't match: $matrix_1_columns != $matrix_2_rows"; } my $result = []; my ($i, $j, $k); for $i (range($matrix_1_rows)) { for $j (range($matrix_2_columns)) { for $k (range($matrix_1_columns)) { $result->[$i][$j] += $matrix_1->[$i][$k] * $matrix_2->[$k][$j]; } } } return $result; } sub range { 0 .. ($_[0] - 1) } sub vector_length { my $array_reference = $_[0]; my $type = ref $array_reference; if ($type ne "ARRAY") { die "$type is bad array ref for $array_refer +ence" } return scalar(@$array_reference); } sub matrix_dimension { my $matrix = $_[0]; my $rows = vector_length($matrix); my $columns = vector_length($matrix->[0]); return ($rows, $columns); }
I would like to print a matrix, not an array reference. Could you tell me how to do this? (it's my worst perl nightmare, tried to do something myself but successfully failed every time)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: matrix multiplication
by luis.roca (Deacon) on Nov 18, 2011 at 18:25 UTC | |
|
Re: matrix multiplication
by hbm (Hermit) on Nov 18, 2011 at 17:17 UTC | |
|
Re: matrix multiplication
by johnny_carlos (Scribe) on Nov 18, 2011 at 17:01 UTC | |
|
Re: matrix multiplication
by ambrus (Abbot) on Nov 19, 2011 at 17:48 UTC | |
by marioroy (Prior) on Feb 18, 2013 at 23:34 UTC |