I have a small script to multiply two matrices together (and no this is not homework, I'm just puttering around with Perl). I have a problem with it that I have been unable to resolve.
matrix_count_rows_cols($r_mat1) is consistently returning 0 rows and 0 columns. Not sure why. Any ideas? (Please keep in mind I'm still pretty green when it comes to Perl). Thanks in advance
use strict 'vars';
use strict 'subs';
use warnings;
my @matrix1=(
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
);
my @matrix2=(
[2, 4, 6],
[1, 3, 5],
[7, 8, 9]
);
print "matrix1=\n";
for (my $i=0;$i le 2;$i++) {
for (my $j=0;$j le 2;$j++) {
print $matrix1[$i][$j]," ";
}
print "\n";
}
print "matrix2=\n";
for (my $i=0;$i le 2;$i++) {
for (my $j=0;$j le 2;$j++) {
print $matrix2[$i][$j]," ";
}
print "\n";
}
my @product=matrix_multiply(@matrix1,@matrix2);
print "product=\n";
for (my $i=0;$i le 2;$i++) {
for (my $j=0;$j le 2;$j++) {
print $product[$i][$j]," ";
}
print "\n";
}
sub matrix_multiply {
my ($r_mat1,$r_mat2)=@_;
my ($r_product);
my ($r1,$c1)=matrix_count_rows_cols($r_mat1);
my ($r2,$c2)=matrix_count_rows_cols($r_mat2);
print $c1,$c2,"\n";
print $r1,$r2,"\n";
die "matrix 1 has $c1 columns and matrix 2 has $r2 rows>"
. " Cannot multiply\n" unless ($c1==$r2);
for (my $i=0;$i<$r1;$i++) {
for (my $j=0;$j<$c2;$j++) {
my $sum=0;
for (my $k=0;$k<$c1;$k++) {
$sum+=$r_mat1->[$i][$k]*$r_mat2->[$k][$j];
}
$r_product->[$i][$j]=$sum;
}
}
$r_product;
}
sub matrix_count_rows_cols {
my ($r_mat)=@_;
my $num_rows=@$r_mat;
my $num_cols=@{$r_mat->[0]};
($num_rows,$num_cols);
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.