Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY^605


MATRIX MANIPULATION


Problem:Many mathematical problems, such as rotations in graphics, require the addi-
tion, subtraction, and multiplication of two matrices. Design and implement a general-
purpose Matrixclass that provides the operations addition, subtraction, and
multiplication for real matrices.


Brainstorming:We are not asked to solve a problem in this Case Study; rather, we are
asked to produce a class for the library. We have to create a test driver to be sure the
class works properly, but we do not need to deliver it to the client. Thus our usual
pattern of object-oriented problem solving is not appropriate here.


Background:You reach for your algebra book to refresh your memory on what matrices
are and how matrix addition, subtraction, and multiplication work. You find that a ma-
trix is just like an array data type—well, not exactly. A matrix is a mathematical object;
an array is a structured data type. A more accurate statement is that an array is a
perfect structure to implement a matrix.
Before we start to design the user interface for the Matrixclass, we review what the
operations on matrices mean. To add two matrices, you add the values in the
corresponding positions: result[i][j] = A[i][j] + B[i][j]. To subtract one matrix from
another, you subtract the values in the corresponding positions: result[i][j] = A[i][j] 
B[i][j]. A + B and A B are only defined on matrices with the same dimensions.


Matrix multiplication is slightly more complex. If matrix E is the result of
multiplying matrices C and D, then


E[i][j] = C[i][1]*D[1][j] + C[i][2]*D[2][j] + ...+ C[i][n]*D[n][j].

Why didn’t we use the same matrices, A and B, for multiplication that we used for addi-
tion and subtraction? Well, matrices A and B cannot be multiplied. Look carefully at the
formula: The first row of C is multiplied item by item by the first column of D and the
values summed. Therefore, the number of columns in C must be equal to the number of
rows in D. Here is an example:


A = 5
2
1
1
2

0
1
1
2
3

1
3
0
3
1

4
2
0
4
0

B = 1
2
1
0
0

1
1
2
0
0

1
0
4
4
1

2
3
1
5
1
A + B = 6
4
2
1
2

1
2
3
2
3

2
3
4
7
2

6
5
1
9
1

A – B = 4
0
0
1
2


  • 1
    0

  • 1
    2
    3


0
3


  • 4

  • 1
    0


2


  • 1

  • 1

  • 1

  • 1

Free download pdf