saru
Novice
Oct 30, 2013, 1:53 AM
Post #1 of 2
(10577 views)

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)
