CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Need a Custom or Prewritten Perl Program?: I need a program that...:
Matrix

 



saru
Novice

Oct 30, 2013, 1:53 AM

Post #1 of 2 (9963 views)
Matrix Can't Post

Consider example(down) and complete
the functions matAdd (matrix addition) and matMul (matrix multiplication) . Both functions have two parameters, which are the references to the two matrices to be
added or multiplied. The function should return the resulting matrix. Assume that the functions
always get valid matrices as input (the different row arrays have exactly the same number of
elments, etc.). The dimensions of the supplied matrices for the operation (add or multiply),
however, may make sense or not. Therfore, check, whether the operation makes sense; in case
it does not make sense, write an error message to the output. Finally execute the prepared script
and check whether your operations give the correct results.

#!/usr/bin/perl
use strict;
use warnings;

sub matAdd {
my $refToMat1=$_[0];
my $refToMat2=$_[1];
my $rows1=$#{$refToMat1}+1;
my $cols1=$#{${$refToMat1}[0]}+1;
my $rows2=$#{$refToMat2}+1;
my $cols2=$#{${$refToMat2}[0]}+1;
#Access to matrix element ${$refToMat1}[$i][$j]
#Complete
}

sub matMul {
my $refToMat1=$_[0];
my $refToMat2=$_[1];
#Complete
}

print "\n\n\n";


my @mat1 = ([1, 2, 3], [4, 5, 6], [7, 8, 9], [2, 1, 3]);
my @mat2 = ([1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]);
my @resAdd = matAdd(\@mat1, \@mat1);
my @resMult = matMul(\@mat1, \@mat2);

my $i;
my $j;

print "Matrix add:\n";
for $i ( 0 .. $#resAdd ) {
for $j ( 0 .. $#{$resAdd[$i]} ) {
printf "%10.1f, ", $resAdd[$i][$j];
}
print "\n";
}

print "Matrix multiplication:\n";
for $i ( 0 .. $#resMult ) {
for $j ( 0 .. $#{$resMult[$i]} ) {
printf "%10.1f, ", $resMult[$i][$j];
}
print "\n";
}


(This post was edited by saru on Oct 30, 2013, 10:43 AM)


BillKSmith
Veteran

Oct 31, 2013, 5:29 AM

Post #2 of 2 (9924 views)
Re: [saru] Matrix [In reply to] Can't Post

A very quick search of CPAN finds Math::Matrix. It has an object oriented interface similar to what you want. I am fairly certain that a more diligent hunt would find others even more to your liking.
Good Luck,
Bill

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives