Category: | Miscellaneous |
Author/Contact Info | Zenon Zabinski | zdog7@hotmail.com |
Description: | Being in Algebra II, my class is learning about matrices. Finding that multiplying matrices takes so long, I automated it using Perl with this script. Suggestions are not only welcomed, but wanted! Thanks to jcwren, jlp, BlaisePascal, and merlyn's Programming Perl for helping me out. |
#!/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 matr +ix # followed by an <ENTER> with each element separated by a # space. After you have no more rows left, press enter with +out # 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 (<STDIN>) { 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; } |
|
---|
Replies are listed 'Best First'. | |
---|---|
RE: Matrix Multiplier
by Cirollo (Friar) on Sep 09, 2000 at 09:01 UTC | |
by BlaisePascal (Monk) on Sep 10, 2000 at 07:57 UTC | |
by merlyn (Sage) on Sep 10, 2000 at 12:47 UTC | |
RE: Matrix Multiplier
by BlaisePascal (Monk) on Sep 10, 2000 at 08:49 UTC | |
by tilly (Archbishop) on Sep 10, 2000 at 16:38 UTC | |
RE (tilly) 1: Matrix Multiplier
by tilly (Archbishop) on Sep 09, 2000 at 14:30 UTC |
Back to
Code Catacombs