## WeBWorK Problems

### Re: Some WeBWorK (Perl) code for Matrix Math Objects

by Christopher Heckman -
Number of replies: 0
In this post: a Mat2System that works with MathObjects.

Syntax: Mat2System ($A, @variable_list,$b) displays a system of linear equations, where

$A is a Matrix $b is a Matrix or a Vector (or a ColumnVector)
@variable_list is a (Perl) list of strings (variable names)

Example usage:

Mat2System (Matrix ([[1,2],[3,4]], "x", "y", Vector([5,6]))
Mat2System (Matrix ([[1,2,3],[4,5,6]], qw ("x_1 x_2 x_3 "), Matrix([[1],[2]]))

Code: (Free to use, as long as you credit me and Thomas Hagedorn (who wrote the original version))

sub Mat2System{ # Mat2System (A, qw(x y z w), b)
   my $coeffs = shift;  my @vec = @_;  my$vname = pop @vec;
   my ($srow,$scol) = $coeffs->dimensions;  my$vnamerow = scalar @vec;
   my $vrow;  if ($vname -> class eq "Matrix") { $vrow = ($vname->dimensions)[0] }
   if ($vname -> class eq "Vector") {$vrow = $vname -> length; }  die "Wrong number of rows or columns2" if ($vrow != $srow);  die "Wrong number of rows or columns4" if ($scol != $vnamerow);  my$outstr="\begin{array}";
   my $s; $outstr .= '{' . ('r' x (2 * $scol + 2)) . '}';  for (my$j = 0; $j <$srow; $j ++) {  $s = 0;
      for (my $i = 0;$i < $scol;$i++) {
         my $varname =$vec [$i];   my$a = $coeffs->element ($j + 1, $i + 1);   if ($a == 0) {
            if (($s > 0) || ($i < $scol - 1)) {$outstr .= '&&'; }
            else { $outstr .= '&0'; }  }  elsif ($a > 0) {
            if ($a == 1) {$a = ""; }
            if ($s==0) {$outstr .= "& $a \,$varname"; $s = 1; }  else {$outstr .= "&+& $a \,$varname"; }
            }
         else {
            if ($s == 1) {  $a = -$a;   if ($a == 1) { $a = ""; }  $outstr .= "&- &$a \,$varname";
               }
            else {
               if ($a == -1) {$a = "-"; }
               $outstr =$outstr . "& $a \,$varname"; $s = 1;  }  }   }   if ($vname -> class eq "Matrix") { $outstr .= "&=&" .$vname->element($j+1, 1). "\\"; }  if ($vname -> class eq "Vector") { $outstr .= "&=&" .$vname->extract ($j+1). "\\"; }  }  $outstr . ' \end{array}';
   }