Java Reference
In-Depth Information
Listing 19.13 gives a program that creates two Integer matrices (lines 4-5) and an
IntegerMatrix object (line 8), and adds and multiplies two matrices in lines 12 and 16.
L ISTING 19.13
TestIntegerMatrix.java
1 public class TestIntegerMatrix {
2 public static void main(String[] args) {
3 // Create Integer arrays m1, m2
4 Integer[][] m1 = new Integer[][]{{ 1 , 2 , 3 }, { 4 , 5 , 6 }, { 1 , 1 , 1 }};
5 Integer[][] m2 = new Integer[][]{{ 1 , 1 , 1 }, { 2 , 2 , 2 }, { 0 , 0 , 0 }};
6
7 // Create an instance of IntegerMatrix
8 IntegerMatrix integerMatrix = new IntegerMatrix();
9
10 System.out.println( "\nm1 + m2 is " );
11 GenericMatrix.printResult(
12 m1, m2, integerMatrix.addMatrix(m1, m2), '+' );
13
14 System.out.println( "\nm1 * m2 is " );
15 GenericMatrix.printResult(
16 m1, m2, integerMatrix.multiplyMatrix(m1, m2), '*' );
17 }
18 }
create matrices
create IntegerMatrix
add two matrices
multiply two matrices
m1 + m2 is
1 2 3 1 1 1 2 3 4
4 5 6 + 2 2 2 = 6 7 8
1 1 1 0 0 0 1 1 1
m1 * m2 is
1 2 3 1 1 1 5 5 5
4 5 6 * 2 2 2 = 14 14 14
1 1 1 0 0 0 3 3 3
Listing 19.14 gives a program that creates two Rational matrices (lines 4-10) and a
RationalMatrix object (line 13) and adds and multiplies two matrices in lines 17 and 19.
L ISTING 19.14
TestRationalMatrix.java
1 public class TestRationalMatrix {
2 public static void main(String[] args) {
3 // Create two Rational arrays m1 and m2
4 Rational[][] m1 = new Rational[ 3 ][ 3 ];
5 Rational[][] m2 = new Rational[ 3 ][ 3 ];
6 for ( int i = 0 ; i < m1.length; i++)
7 for ( int j = 0 ; j < m1[ 0 ].length; j++) {
8 m1[i][j] = new Rational(i + 1 , j + 5 );
9 m2[i][j] = new Rational(i + 1 , j + 6 );
10 }
11
12 // Create an instance of RationalMatrix
13 RationalMatrix rationalMatrix = new RationalMatrix();
14
15 System.out.println( "\nm1 + m2 is " );
16 GenericMatrix.printResult(
17 m1, m2, rationalMatrix.addMatrix(m1, m2), '+' );
18
19 System.out.println( "\nm1 * m2 is " );
create matrices
create RationalMatrix
add two matrices
 
 
Search WWH ::




Custom Search