Java Reference
In-Depth Information
In order to be added, the two matrices must have the same dimensions and the
same or compatible types of elements. Let c be the resulting matrix. Each ele-
ment c ij is a ij
+
b ij . For example, for two 3
*
3 matrices a and b , c is
£ a 11
a 12
a 13
£ b 11
b 12
b 13
£ a 11
+
b 11
a 12
+
b 12
a 13
+
b 13
a 21
a 22
a 23
+
b 21
b 22
b 23
=
a 21
+
b 21
a 22
+
b 22
a 23
+
b 23
VideoNote
Multiply two matrices
a 31
a 32
a 33
b 31
b 32
b 33
a 31
+
b 31
a 32
+
b 32
a 33
+
b 33
Write a test program that prompts the user to enter two 3
*
3 matrices and
displays their sum. Here is a sample run:
Enter matrix1: 1 2 3 4 5 6 7 8 9
Enter matrix2: 0 2 4 1 4.5 2.2 1.1 4.3 5.2
The matrices are added as follows
1.0 2.0 3.0 0.0 2.0 4.0 1.0 4.0 7.0
4.0 5.0 6.0 + 1.0 4.5 2.2 = 5.0 9.5 8.2
7.0 8.0 9.0 1.1 4.3 5.2 8.1 12.3 14.2
**8.6
( Algebra: multiply two matrices ) Write a method to multiply two matrices. The
header of the method is:
public static double [][]
multiplyMatrix( double [][] a, double [][] b)
To multiply matrix a by matrix b , the number of columns in a must be the same as
the number of rows in b , and the two matrices must have elements of the same or
compatible types. Let c be the result of the multiplication. Assume the column size
of matrix a is n . Each element c ij is a i 1
*
b 1 j
+
a i 2
*
b 2 j
+ c +
a in
*
b nj .
For example, for two 3
*
3 matrices a and b , c is
£ a 11
a 12
a 13
£ b 11
b 12
b 13
£ c 11
c 12
c 13
a 21
a 22
a 23
*
b 21
b 22
b 23
=
c 21
c 22
c 23
a 31
a 32
a 33
b 31
b 32
b 33
c 31
c 32
c 33
where c ij =
*
+
*
+
*
a i 1
b 1 j
a i 2
b 2 j
a i 3
b 3 j .
*
Write a test program that prompts the user to enter two 3
3 matrices and dis-
plays their product. Here is a sample run:
Enter matrix1: 1 2 3 4 5 6 7 8 9
Enter matrix2: 0 2 4 1 4.5 2.2 1.1 4.3 5.2
The multiplication of the matrices is
1 2 3 0 2.0 4.0 5.3 23.9 24
4 5 6 * 1 4.5 2.2 = 11.6 56.3 58.2
7 8 9 1.1 4.3 5.2 17.9 88.7 92.4
*8.7
( Points nearest to each other ) Listing 8.3 gives a program that finds two points in a
two-dimensional space nearest to each other. Revise the program so that it finds two
points in a three-dimensional space nearest to each other. Use a two-dimensional
array to represent the points. Test the program using the following points:
double [][] points = {{ -1 , 0 , 3 }, { -1 , -1 , -1 }, { 4 , 1 , 1 },
{ 2 , 0.5 , 9 }, { 3.5 , 2 , -1 }, { 3 , 1.5 , 3 }, { -1.5 , 4 , 2 },
{ 5.5 , 4 , -0.5 }};
 
Search WWH ::




Custom Search