Quick Navigator

 Search Site Miscellaneous Server Agreement Year 2038 Credits

# Manual Reference Pages  -  MATH::MATRIXREAL (3)

.ds Aq ’

### NAME

Math::MatrixReal - Matrix of Reals

Implements the data type "matrix of real numbers" (and consequently also "vector of real numbers").

### SYNOPSIS

my $a = Math::MatrixReal->new_random(5, 5); my$b = $a->new_random(10, 30, { symmetric=>1, bounded_by=>[-1,1] }); my$c = $b *$a ** 3;

my $d =$b->new_from_rows( [ [ 5, 3 ,4], [3, 4, 5], [ 2, 4, 1 ] ] );

print $a; my$row = ($a *$b)->row(3);

my $col = (5*$c)->col(2);

my $transpose = ~$c;

my $transpose =$c->transpose;

my $inverse =$a->inverse;

my $inverse = 1/$a;

my $inverse =$a ** -1;

my $determinant=$a->det;
o $matrix->display_precision($integer)

Sets the default precision when matrices are printed or stringified. $matrix->display_precision(0) will only show the integer part of all the entries of$matrix and $matrix->display_precision() will return to the default scientific display notation. This method does not effect the precision of the calculations. ### FUNCTIONS #### Constructor Methods And Such o use Math::MatrixReal; Makes the methods and overloaded operators of this module available to your program. o$new_matrix = new Math::MatrixReal($rows,$columns);

The matrix object constructor method. A new matrix of size $rows by$columns will be created, with the value 0.0 for all elements.

Note that this method is implicitly called by many of the other methods in this module.

o $new_matrix =$some_matrix->new($rows,$columns);

Another way of calling the matrix object constructor method.

Matrix $some_matrix is not changed by this in any way. o$new_matrix = $matrix->new_from_cols( [$column_vector|$array_ref|$string, ... ] )

Creates a new matrix given a reference to an array of any of the following:
o column vectors ( n by 1 Math::MatrixReal matrices )
o references to arrays
o strings properly formatted to create a column with Math::MatrixReal’s new_from_string command

You may mix and match these as you wish. However, all must be of the same dimension—no padding happens automatically. Example:



my $matrix = Math::MatrixReal->new_from_cols( [ [1,2], [3,4] ] ); print$matrix;



will print



[  1.000000000000E+00  3.000000000000E+00 ]
[  2.000000000000E+00  4.000000000000E+00 ]


o new_from_rows( [ $row_vector|$array_ref|$string, ... ] ) Creates a new matrix given a reference to an array of any of the following: o row vectors ( 1 by n Math::MatrixReal matrices ) o references to arrays o strings properly formatted to create a row with Math::MatrixReal’s new_from_string command You may mix and match these as you wish. However, all must be of the same dimension—no padding happens automatically. Example:  my$matrix = Math::MatrixReal->new_from_rows( [ [1,2], [3,4] ] );
print $matrix;  will print  [ 1.000000000000E+00 2.000000000000E+00 ] [ 3.000000000000E+00 4.000000000000E+00 ]  o$new_matrix = Math::MatrixReal->new_random($rows,$cols, %options );

This method allows you to create a random matrix with various properties controlled by the %options matrix, which is optional. The default values of the %options matrix are { integer => 0, symmetric => 0, tridiagonal => 0, diagonal => 0, bounded_by => [0,10] } .



Example:

$matrix = Math::MatrixReal->new_random(4, { diagonal => 1, integer => 1 } ); print$matrix;



will print a 4x4 random diagonal matrix with integer entries between zero and ten, something like



[  5.000000000000E+00  0.000000000000E+00  0.000000000000E+00  0.000000000000E+00 ]
[  0.000000000000E+00  2.000000000000E+00  0.000000000000E+00  0.000000000000E+00 ]
[  0.000000000000E+00  0.000000000000E+00  1.000000000000E+00  0.000000000000E+00 ]
[  0.000000000000E+00  0.000000000000E+00  0.000000000000E+00  8.000000000000E+00 ]


o $new_matrix = Math::MatrixReal->new_diag($array_ref );

This method allows you to create a diagonal matrix by only specifying the diagonal elements. Example:



$matrix = Math::MatrixReal->new_diag( [ 1,2,3,4 ] ); print$matrix;



will print



[  1.000000000000E+00  0.000000000000E+00  0.000000000000E+00  0.000000000000E+00 ]
[  0.000000000000E+00  2.000000000000E+00  0.000000000000E+00  0.000000000000E+00 ]
[  0.000000000000E+00  0.000000000000E+00  3.000000000000E+00  0.000000000000E+00 ]
[  0.000000000000E+00  0.000000000000E+00  0.000000000000E+00  4.000000000000E+00 ]


o $new_matrix = Math::MatrixReal->new_tridiag($lower, $diag,$upper );

This method allows you to create a tridiagonal matrix by only specifying the lower diagonal, diagonal and upper diagonal, respectively.



$matrix = Math::MatrixReal->new_tridiag( [ 6, 4, 2 ], [1,2,3,4], [1, 8, 9] ); print$matrix;



will print



[  1.000000000000E+00  1.000000000000E+00  0.000000000000E+00  0.000000000000E+00 ]
[  6.000000000000E+00  2.000000000000E+00  8.000000000000E+00  0.000000000000E+00 ]
[  0.000000000000E+00  4.000000000000E+00  3.000000000000E+00  9.000000000000E+00 ]
[  0.000000000000E+00  0.000000000000E+00  2.000000000000E+00  4.000000000000E+00 ]


o $new_matrix = Math::MatrixReal->new_from_string($string);

This method allows you to read in a matrix from a string (for instance, from the keyboard, from a file or from your code).

The syntax is simple: each row must start with "[ and end with ]\n (\n being the newline character and " a space or tab) and contain one or more numbers, all separated from each other by spaces or tabs.

Examples:



$string = "[ 1 2 3 ]\n[ 2 2 -1 ]\n[ 1 1 1 ]\n";$matrix = Math::MatrixReal->new_from_string($string); print "$matrix";



By the way, this prints



[  1.000000000000E+00  2.000000000000E+00  3.000000000000E+00 ]
[  2.000000000000E+00  2.000000000000E+00 -1.000000000000E+00 ]
[  1.000000000000E+00  1.000000000000E+00  1.000000000000E+00 ]



But you can also do this in a much more comfortable way using the shell-like here-document syntax:



$matrix = Math::MatrixReal->new_from_string(<<MATRIX); [ 1 0 0 0 0 0 1 ] [ 0 1 0 0 0 0 0 ] [ 0 0 1 0 0 0 0 ] [ 0 0 0 1 0 0 0 ] [ 0 0 0 0 1 0 0 ] [ 0 0 0 0 0 1 0 ] [ 1 0 0 0 0 0 -1 ] MATRIX  You can even use variables in the matrix: $c1 =   2  /  3;
$c2 = -2 / 5;$c3 =  26  /  9;

$matrix = Math::MatrixReal->new_from_string(<<"MATRIX"); [ 3 2 0 ] [ 0 3 2 ] [$c1  $c2$c3  ]

MATRIX



(Remember that you may use spaces and tabs to format the matrix to your taste)

Note that this method uses exactly the same representation for a matrix as the stringify operator "": this means that you can convert any matrix into a string with $string = "$matrix"; and read it back in later (for instance from a file!).

Note however that you may suffer a precision loss in this process because only 13 digits are supported in the mantissa when printed!!

If the string you supply (or someone else supplies) does not obey the syntax mentioned above, an exception is raised, which can be caught by eval as follows:



$string = <STDIN>;$string =~ s/\\n/\n/g;
eval { $matrix = Math::MatrixReal->new_from_string($string); };
if ($@) { print "$@";
# ...
# (error handling)
}
else
{
# continue...
}



or as follows:



eval { $matrix = Math::MatrixReal->new_from_string(<<"MATRIX"); }; [ 3 2 0 ] [ 0 3 2 ] [$c1  $c2$c3  ]
MATRIX
if ($@) # ...  Actually, the method shown above for reading a matrix from the keyboard is a little awkward, since you have to enter a lot of \n’s for the newlines. A better way is shown in this piece of code:  while (1) { print "\nPlease enter your matrix "; print "(multiple lines, <ctrl-D> = done):\n"; eval {$new_matrix =
Math::MatrixReal->new_from_string(join(,<STDIN>)); };
if ($@) {$@ =~ s/\s+at\b.*?$//; print "${@}Please try again.\n";
}
else { last; }
}



Possible error messages of the new_from_string() method are:



Math::MatrixReal::new_from_string(): syntax error in input string
Math::MatrixReal::new_from_string(): empty input string



If the input string has rows with varying numbers of columns, the following warning will be printed to STDERR:



Math::MatrixReal::new_from_string(): missing elements will be set to zero!



If everything is okay, the method returns an object reference to the (newly allocated) matrix containing the elements you specified.

o $new_matrix =$some_matrix->shadow();

Returns an object reference to a <B>NEWB> but <B>EMPTYB> matrix (filled with zero’s) of the <B>SAME SIZEB> as matrix "$some_matrix". Matrix "$some_matrix" is not changed by this in any way.

o $matrix1->copy($matrix2);

Copies the contents of matrix "$matrix2" to an <B>ALREADY EXISTINGB> matrix "$matrix1 (which must have the same size as matrix $matrix2"!). Matrix "$matrix2" is not changed by this in any way.

o $twin_matrix =$some_matrix->clone();

Returns an object reference to a <B>NEWB> matrix of the <B>SAME SIZEB> as matrix "$some_matrix. The contents of matrix$some_matrix" have <B>ALREADY BEEN COPIEDB> to the new matrix "$twin_matrix. This is the method that the operator =" is overloaded to when you type$a = $b, when$a and $b are matrices. Matrix "$some_matrix" is not changed by this in any way.

o $matrix = Math::MatrixReal->reshape($rows, $cols,$array_ref);

Return a matrix with the specified dimensions ($rows x$cols) whose elements are taken from the array reference $array_ref. The elements of the matrix are accessed in column-major order (like Fortran arrays are stored). $matrix = Math::MatrixReal->reshape(4, 3, [1..12]);



Creates the following matrix:



[ 1    5    9 ]
[ 2    6   10 ]
[ 3    7   11 ]
[ 4    8   12 ]



#### Matrix Row, Column and Element operations

 o $value =$matrix->element($row,$column); Returns the value of a specific element of the matrix "$matrix, located in row$row and column $column". NOTE:B> Unlike Perl, matrices are indexed with base-one indexes. Thus, the first element of the matrix is placed in the firstB> line, firstB> column: $elem = $matrix->element(1, 1); # first element of the matrix.  o$matrix->assign($row,$column,$value); Explicitly assigns a value "$value to a single element of the matrix $matrix, located in row$row and column $column", thereby replacing the value previously stored there. o$row_vector = $matrix->row($row); This is a projection method which returns an object reference to a NEWB> matrix (which in fact is a (row) vector since it has only one row) to which row number "$row of matrix$matrix" has already been copied. Matrix "$matrix" is not changed by this in any way. o$column_vector = $matrix->column($column); This is a projection method which returns an object reference to a NEWB> matrix (which in fact is a (column) vector since it has only one column) to which column number "$column of matrix$matrix" has already been copied. Matrix "$matrix" is not changed by this in any way. o @all_elements =$matrix->as_list; Get the contents of a Math::MatrixReal object as a Perl list. Example:  my $matrix = Math::MatrixReal->new_from_rows([ [1, 2], [3, 4] ]); my @list =$matrix->as_list; # 1, 2, 3, 4  o $new_matrix =$matrix->each( \&function ); Creates a new matrix by evaluating a code reference on each element of the given matrix. The function is passed the element, the row index and the column index, in that order. The value the function returns ( or the value of the last executed statement ) is the value given to the corresponding element in $new_matrix. Example:  # add 1 to every element in the matrix$matrix = $matrix->each ( sub { (shift) + 1 } );  Example:  my$cofactor = $matrix->each( sub { my(undef,$i,$j) = @_; ($i+$j) % 2 == 0 ?$matrix->minor($i,$j)->det() : -1*$matrix->minor($i,$j)->det(); } );  This code needs some explanation. For each element of$matrix, it throws away the actual value and stores the row and column indexes in $i and$j. Then it sets element [$i,$j] in $cofactor to the determinant of$matrix->minor($i,$j) if it is an even element, or -1*$matrix->minor($i,$j) if it is an odd element. o$new_matrix = $matrix->each_diag( \&function ); Creates a new matrix by evaluating a code reference on each diagonal element of the given matrix. The function is passed the element, the row index and the column index, in that order. The value the function returns ( or the value of the last executed statement ) is the value given to the corresponding element in$new_matrix. o $matrix->swap_col($col1, $col2 ); This method takes two one-based column numbers and swaps the values of each element in each column.$matrix->swap_col(2,3) would replace column 2 in $matrix with column 3, and replace column 3 with column 2. o$matrix->swap_row( $row1,$row2 ); This method takes two one-based row numbers and swaps the values of each element in each row. $matrix->swap_row(2,3) would replace row 2 in$matrix with row 3, and replace row 3 with row 2. o $matrix->assign_row($row_number , $new_row_vector ); This method takes a one-based row number and assigns row$row_number of $matrix with$new_row_vector and returns the resulting matrix. $matrix->assign_row(5,$x) would replace row 5 in $matrix with the row vector$x. o $matrix->maximum(); and$matrix->minimum(); These two methods work similarly, one for computing the maximum element or elements from a matrix, and the minimum element or elements from a matrix. They work in a similar way as Octave/MatLab max/min functions. When computing the maximum or minimum from a vector (vertical or horizontal), only one element is returned. When computing the maximum or minimum from a matrix, the maximum/minimum element for each column is returned in an array reference. When called in list context, the function returns a pair, where the first element is the maximum/minimum element (or elements) and the second is the position of that value in the vector (first occurrence), or the row where it occurs, for matrices. Consider the matrix and vector below for the following examples:  [ 1 9 4 ] $A = [ 3 5 2 ]$B = [ 8 7 9 5 3 ] [ 8 7 6 ]  When used in scalar context:  $max =$A->maximum(); # $max = [ 8, 9, 6 ]$min = $B->minimum(); #$min = 3  When used in list context:  ($min,$pos) = $A->minimum(); #$min = [ 1 5 2 ] # $pos = [ 1 2 2 ] ($max, $pos) =$B->maximum(); # $max = 9 #$pos = 3 

#### SYNOPSIS

 o Unary operators: "-, ~, abs", test, "!", ’""’ o Binary operators: "." Binary (arithmetic) operators: "+, -, *, **, +=, -=, *=, /=,**=" o Binary (relational) operators: "==, !=, <, <=, >, >=" "eq, ne, lt, le, gt, ge" Note that the latter ("eq, ne, ... ) are just synonyms of the former (==, !=", ... ), defined for convenience only.

#### DESCRIPTION

 ’.’ Concatenation Returns the two matrices concatenated side by side. Example:         $c =$a . $b; For example, if $a=[ 1 2 ] $b=[ 5 6 ] [ 3 4 ] [ 7 8 ] then$c=[ 1 2 5 6 ] [ 3 4 7 8 ]  Note that only matrices with the same number of rows may be concatenated. ’-’ Unary minus Returns the negative of the given matrix, i.e., the matrix with all elements multiplied with the factor -1. Example:  $matrix = -$matrix;  ’~’ Transposition Returns the transposed of the given matrix. Examples:  $temp = ~$vector * $vector;$length = sqrt( $temp->element(1,1) ); if (~$matrix == $matrix) { # matrix is symmetric ... }  abs Norm Returns the one-Norm of the given matrix. Example: $error = abs( $A *$x - $b );  test Boolean test Tests wether there is at least one non-zero element in the matrix. Example:  if ($xn_vector) { # result of iteration is not zero ... }  ’!’ Negated boolean test Tests wether the matrix contains only zero’s. Examples:  if (! $b_vector) { # heterogenous equation system ... } else { # homogenous equation system ... } unless ($x_vector) { # not the null-vector! }  ’‘‘’’‘‘’’’ Stringify operator Converts the given matrix into a string. Uses scientific representation to keep precision loss to a minimum in case you want to read this string back in again later with new_from_string(). By default a 13-digit mantissa and a 20-character field for each element is used so that lines will wrap nicely on an 80-column screen. Examples:  $matrix = Math::MatrixReal->new_from_string(<<"MATRIX"); [ 1 0 ] [ 0 -1 ] MATRIX print "$matrix"; [ 1.000000000000E+00 0.000000000000E+00 ] [ 0.000000000000E+00 -1.000000000000E+00 ] $string = "$matrix"; $test = Math::MatrixReal->new_from_string($string); if ($test ==$matrix) { print ":-)\n"; } else { print ":-(\n"; }  ’+’ Addition Returns the sum of the two given matrices. Examples:  $matrix_S =$matrix_A + $matrix_B;$matrix_A += $matrix_B;  ’-’ Subtraction Returns the difference of the two given matrices. Examples: $matrix_D = $matrix_A -$matrix_B; $matrix_A -=$matrix_B;  Note that this is the same as:  $matrix_S =$matrix_A + -$matrix_B;$matrix_A += -$matrix_B;  (The latter are less efficient, though) ’*’ Multiplication Returns the matrix product of the two given matrices or the product of the given matrix and scalar factor. Examples: $matrix_P = $matrix_A *$matrix_B; $matrix_A *=$matrix_B; $vector_b =$matrix_A * $vector_x;$matrix_B = -1 * $matrix_A;$matrix_B = $matrix_A * -1;$matrix_A *= -1;  ’/’ Division Currently a shortcut for doing $a *$b ** -1 is $a /$b, which works for square matrices. One can also use 1/$a . ’**’ Exponentiation Returns the matrix raised to an integer power. If 0 is passed, the identity matrix is returned. If a negative integer is passed, it computes the inverse (if it exists) and then raised the inverse to the absolute value of the integer. The matrix must be quadratic. Examples: $matrix2 = $matrix ** 2;$matrix **= 2; $inv2 =$matrix ** -2; $ident =$matrix ** 0;  ’==’ Equality Tests two matrices for equality. Example:  if ( $A *$x == $b ) { print "EUREKA!\n"; }  Note that in most cases, due to numerical errors (due to the finite precision of computer arithmetics), it is a bad idea to compare two matrices or vectors this way. Better use the norm of the difference of the two matrices you want to compare and compare that norm with a small number, like this:  if ( abs($A * $x -$b ) < 1E-12 ) { print "BINGO!\n"; }  ’!=’ Inequality Tests two matrices for inequality. Example:  while ($x0_vector !=$xn_vector) { # proceed with iteration ... }  (Stops when the iteration becomes stationary) Note that (just like with the ’==’ operator), it is usually a bad idea to compare matrices or vectors this way. Compare the norm of the difference of the two matrices with a small number instead. ’<’ Less than Examples:  if ( $matrix1 <$matrix2 ) { # ... } if ( $vector <$epsilon ) { # ... } if ( 1E-12 < $vector ) { # ... } if ($A * $x -$b < 1E-12 ) { # ... }  These are just shortcuts for saying:  if ( abs($matrix1) < abs($matrix2) ) { # ... } if ( abs($vector) < abs($epsilon) ) { # ... } if ( abs(1E-12) < abs($vector) ) { # ... } if ( abs($A * $x -$b ) < abs(1E-12) ) { # ... }  Uses the one-norm for matrices and Perl’s built-in abs() for scalars. ’<=’ Less than or equal As with the ’<’ operator, this is just a shortcut for the same expression with abs() around all arguments. Example:  if ( $A *$x - $b <= 1E-12 ) { # ... }  which in fact is the same as:  if ( abs($A * $x -$b ) <= abs(1E-12) ) { # ... }  Uses the one-norm for matrices and Perl’s built-in abs() for scalars. ’>’ Greater than As with the ’<’ and ’<=’ operator, this  if ( $xn -$x0 > 1E-12 ) { # ... }  is just a shortcut for:  if ( abs( $xn -$x0 ) > abs(1E-12) ) { # ... }  Uses the one-norm for matrices and Perl’s built-in abs() for scalars. ’>=’ Greater than or equal As with the ’<’, ’<=’ and ’>’ operator, the following  if ( $LR >=$A ) { # ... }  is simply a shortcut for:  if ( abs($LR) >= abs($A) ) { # ... }  Uses the one-norm for matrices and Perl’s built-in abs() for scalars.

Math::VectorReal, Math::PARI, Math::MatrixBool, Math::Vec, DFA::Kleene, Math::Kleene, Set::IntegerRange, Set::IntegerFast .

### VERSION

This man page documents Math::MatrixReal version 2.10

The latest code can be found at https://github.com/leto/math—matrixreal .

### AUTHORS

Steffen Beyer <sb@engelschall.com>, Rodolphe Ortalo <ortalo@laas.fr>, Jonathan Duke Leto <jonathan@leto.net>.

Currently maintained by Jonathan Duke Leto, send all bugs/patches to Github Issues: https://github.com/leto/math—matrixreal/issues

### CREDITS

Many thanks to Prof. Pahlings for stoking the fire of my enthusiasm for Algebra and Linear Algebra at the university (RWTH Aachen, Germany), and to Prof. Esser and his assistant, Mr. Jarausch, for their fascinating lectures in Numerical Analysis!