1 #!/usr/bin/perl -w 2 3 sub matrixProd { 4 my ($matA, $matB) = @_; 5 my $nRowsA = @{$matA}; 6 my $nColsA = @{$matA->[0]}; 7 my $nRowsB = @{$matB}; 8 my $nColsB = @{$matB->[0]}; 9 my ($matC, $i, $j, $k, $sum); 10 11 if ($nColsA != $nRowsB) { 12 die ("Las dimensiones de las dos matrices no son compatibles\n"); 13 } 14 for($i = 0; $i < $nRowsA; $i++) { 15 for($j = 0; $j < $nColsB; $j++) { 16 $sum = 0; 17 for($k=0; $k < $nColsA; $k++) { 18 $sum += $matA->[$i][$k] * $matB->[$k][$j]; 19 } 20 $matC->[$i][$j] = $sum; 21 } 22 } 23 return $matC; 24 } 25 26 sub printMat { 27 my $mat = shift; 28 my $nRows = @{$mat}; 29 my $nCols = @{$mat->[0]}; 30 my $i = 0; 31 32 for($i = 0; $i < $nRows; $i++) { 33 for($j = 0; $j < $nCols; $j++) { 34 print $mat->[$i][$j], "\t"; 35 } 36 print "\n"; 37 } 38 } 39 40 # 41 # ---- Main ---- 42 # 43 44 $matA = [[1,2,3],[2,4,6],[3,6,9]]; 45 $matB = [[1,2],[2,4],[3,6]]; 46 $matC = matrixProd($matA,$matB); 47 48 print "Matriz A \n"; printMat($matA); 49 print "\nMatriz B \n"; printMat($matB); 50 print "\nMatriz C \n"; printMat($matC);Todo queda mucho mas simple usando el módulo PDL (PDL significa Perl Data Language):
1 #!/usr/bin/perl -w 2 use PDL; 3 4 $a = pdl [[1,2,3],[2,4,6],[3,6,9]]; 5 $b = pdl [[1,2],[2,4],[3,6]]; 6 $c = $a x $b; # x esta sobrecargado 7 8 print "a = $a\nb = $b\nc = $c\n";PDL es un módulo diseñado para el cálculo y visualización de datos científicos.