Computer Science 130
Programming Assignment - Due 7 June
2001
The Inverse of a Square Matrix
Objective of the Program
This program will receive a square matrix from the user.
If the matrix has an inverse, the program will find the inverse and print
the results of multiplying the original matrix by the inverse.
Input
-
The size of the square matrix (# of rows)
-
The values for each position of the matrix
Output
-
An error message if the original matrix has no inverse
-
The inverse (if it exists) and the product of the inverse
matrix and the original matrix
Useful Information
-
The inverse of a matrix is another matrix that when you multiply
those two matrices together you get the identity matrix as the result.
(see Lab 8 for the definition of the identity matrix)
-
Reuse your code from Lab 8. Much will be the same between
that lab and this one.
-
How do you find the inverse of a matrix? By using the
same Gaussian Elimination techniques you used for Lab 8 (multiply row by
constant, add multiple of one row to another, switch two rows). For
example, if I want to find the inverse of the matrix:
I would:
(1) Concatenate the identity matrix
on to the end of this matrix:
| 0 |
1 |
1 |
1 |
0 |
0 |
| 1 |
0 |
1 |
0 |
1 |
0 |
| 1 |
1 |
0 |
0 |
0 |
1 |
(2) Use Gaussian Elimination
to turn the left part of the matrix into the identity matrix:
(Refer back to Lab 8 for a step-by-step explanation)
| 1 |
0 |
1 |
0 |
1 |
0 |
| 0 |
1 |
1 |
1 |
0 |
0 |
| 0 |
1 |
-1 |
0 |
-1 |
1 |
| 1 |
0 |
1 |
0 |
1 |
0 |
| 0 |
1 |
1 |
1 |
0 |
0 |
| 0 |
0 |
-2 |
-1 |
-1 |
1 |
| 1 |
0 |
0 |
-0.5 |
0.5 |
0.5 |
| 0 |
1 |
0 |
0.5 |
-0.5 |
0.5 |
| 0 |
0 |
1 |
0.5 |
0.5 |
-0.5 |
The results on the right part of the matrix are
the inverse to the original matrix. To verify this, you can multiply
by
| -0.5 |
0.5 |
0.5 |
| 0.5 |
-0.5 |
0.5 |
| 0.5 |
0.5 |
-0.5 |
and see that the result is the identity matrix.
-
What if you get stuck with a 0 on the main diagonal?
That means that the matrix does not have an inverse. Print that error
message and end the program.
-
How do you multiply two matrices together? Multiply
each row of the first matrix by each column of the second matrix to generate
the answers. For example, if we were to multiply
matrix A
by matrix B
| -0.5 |
0.5 |
0.5 |
| 0.5 |
-0.5 |
0.5 |
| 0.5 |
0.5 |
-0.5 |
then in the result matrix, row 1, column 0 is
found by multiplying row 1 of matrix A by column 0 of matrix B and adding
the terms together. Row 1 of matrix A is (1,0,1). Column 0
of matrix B is (-0.5,0.5,0.5). Multiplying them produces: (1 * -0.5)
+ (0 * 0.5) + (1 * 0.5) = 0
So the result matrix has 0 in row 1, column 0.
Repeating this process for the other rows of matrix A and the other columns
of matrix B gives the product:
Return to the Block 3 Index
Return to the Lab Index
Return to the CS 130 Homepage