#!/usr/bin/perl -w # # Title : Matrix Multiplier # Author : Zenon Zabinski # E-Mail : zdog7@hotmail.com # # Versions : 1.00 - Initial product, pun intended # 1.10 - With several optimizations # # Help : When prompted for each matrix, enter each row of the matrix # followed by an with each element separated by a # space. After you have no more rows left, press enter without # typing anything when prompted for the next row. The only keys # you should use are: enter, space, and the numbers. Happy # matrix multiplying. :-) # # Copyright (C) 2000 Zenon Zabinski. No rights reserved. # use strict; my (@firstfactor, @secondfactor, @product); @firstfactor = getmatrix ("First"); @secondfactor = getmatrix ("Second"); @product = getproduct (\@firstfactor, \@secondfactor); printmatrix (@product); # SUBS: sub getmatrix { my @matrix; print "\n". shift() ." matrix:\n"; while () { chop; last if (!$_); if (/[^0-9 ]/) { die "Not a legal matrix row!\n"; } push @matrix, [ split / / ]; } return @matrix; } sub checkmatrix { my $rowlength = $#{$_[0]}; for (@_) { $rowlength == $#$_ or die "Number of columns was not consistent!\n"; } } sub printmatrix { foreach (@_) { print "[ "; printf("%-4s", " $_") foreach (@$_); print " ]\n"; } } sub getdimen { my $rows = @_; my $cols = $#{$_[0]}; return ($rows - 1, $cols); } sub getproduct { my ($a, $b) = @_; my @product; checkmatrix(@$a); checkmatrix(@$b); my ($arow, $acol) = getdimen(@$a); my ($brow, $bcol) = getdimen(@$b); $acol == $brow or die "The matrices can't be multiplied!\n"; for my $i (0..$arow) { for my $j (0..$bcol) { for my $k (0..$acol) { $product[$i][$j] += $$a[$i][$k] * $$b[$k][$j]; } } } return @product; }