#################################################################### ## 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)
In reply to matrix multiplication by etheral
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |