Java Reference
In-Depth Information
Solution
Use the following code as a model.
Discussion
It is straightforward to multiply an array of a numeric type. The code in
Example 5-5
imple-
ments matrix multiplication.
Example 5-5. Matrix.java
public
public class
class
Matrix
Matrix
{
/* Matrix-multiply two arrays together.
* The arrays MUST be rectangular.
* @author Tom Christiansen & Nathan Torkington, Perl Cookbook version.
*/
public
public static
static
int
int
[][]
multiply
(
int
int
[][]
m1
,
int
int
[][]
m2
) {
int
int
m1rows
=
m1
.
length
;
int
int
m1cols
=
m1
[
0
].
length
;
int
int
m2rows
=
m2
.
length
;
int
int
m2cols
=
m2
[
0
].
length
;
iif
(
m1cols
!=
m2rows
)
throw
throw new
new
IllegalArgumentException
(
"matrices don't match: "
+
m1cols
+
" != "
+
m2rows
);
int
int
[][]
result
=
new
new
int
int
[
m1rows
][
m2cols
];
// multiply
for
for
(
int
int
i
=
0
;
i
<
m1rows
;
i
++) {
for
for
(
int
int
j
=
0
;
j
<
m2cols
;
j
++) {
for
for
(
int
int
k
=
0
;
k
<
m1cols
;
k
++) {
result
[
i
][
j
] +=
m1
[
i
][
k
] *
m2
[
k
][
j
];
}
}
}
return
return
result
;
}
/** Matrix print.
*/
public
public static
static
void
void
mprint
(
int
int
[][]
a
) {
int
int
rows
=
a
.
length
;
int
int
cols
=
a
[
0
].
length
;
System
.
out
.
println
(
"array["
+
rows
+
"]["
+
cols
+
"] = {"
);