Sec2-3-InvertMatrix.mws

Linear Algebra Powertool

Finding the Inverse of a Matrix

Worksheet by Russell Blyth

> with(linalg):

Warning, the protected names norm and trace have been redefined and unprotected

Enter matrix to be inverted

> A:=matrix([[1,4,-1],[-2,0,3],[3,6,1]]);

A := matrix([[1, 4, -1], [-2, 0, 3], [3, 6, 1]])

>

Augment the matrix by appending the identity

> K:=augment(A,[1,0,0],[0,1,0],[0,0,1]);

K := matrix([[1, 4, -1, 1, 0, 0], [-2, 0, 3, 0, 1, ...

>

Reduce the augmented matrix to reduced row echelon form

> K:=rref(K);

K := matrix([[1, 0, 0, -9/19, -5/19, 6/19], [0, 1, ...

>

If the n x n identity appears in the first n columns of the matrix, the last n x n columns is the inverse; extract it using the submatrix command

> AINV:=submatrix(K,1..3,4..6);

AINV := matrix([[-9/19, -5/19, 6/19], [11/38, 2/19,...

>

Check the result:

> evalm(A &* AINV);

matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])

> evalm(AINV &* A);

matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])

>

The linalg package has a built-in inverse command

> inverse(A);

matrix([[-9/19, -5/19, 6/19], [11/38, 2/19, -1/38],...

>

If the matrix has no inverse, the procedure above will not give the nx n identity in the first n x n columns of K. Here is how the inverse function behaves:

> B:=matrix([[2,4],[4,8]]);

B := matrix([[2, 4], [4, 8]])

>

> inverse(B);

Error, (in inverse) singular matrix

The linalg package includes a routine to generate random matrices with integer entries, for testing purposes. Let's use it to generate matrices and inverses.

> C:=randmatrix(4,4);

C := matrix([[-85, -55, -37, -35], [97, 50, 79, 56]...

>

> inverse(C);

matrix([[367657/2912996, 199729/2912996, 179387/291...

>

By default, the entries of the randomly generated matrix fall between -99 and 99. An option can be added to specify the allowed range.

> E:=randmatrix(4,4,entries=rand(-5..5));

E := matrix([[1, 5, -2, 3], [-5, -5, 1, 5], [-2, 3,...

>

(The variable name D is protected, and is used for the differential operator)

> D(x^2);

2*D(x)*x

> inverse(E);

matrix([[-51/7, -27/14, 46/7, 33/14], [95/14, 47/28...

>

>