Matrix Multiply in Java
1. Matrix multiplication with Outer Product
// Better way to multiply matrix, mul matrix, mult matrix
public static int[][] multiply2(int[][] arr1, int[][] arr2) {
int[][] arr3 = null;
if( arr1 != null && arr2 != null) {
int height = arr1.length;
int width = arr1[0].length;
int len = height;
arr3 = new int[height][height];
for(int k = 0; k < len; k++) {
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
arr3[i][j] += arr1[i][k]*arr2[k][j];
}
}
}
}
return arr3;
}
\begin{equation}
\begin{aligned}
A &= \begin{bmatrix}
1 & 2\\
3 & 4
\end{bmatrix} \quad
B = \begin{bmatrix}
2 & 3\\
4 & 5
\end{bmatrix} \\
&\text{We abuse the inner product notation here:} \\
&\left< u^{\ast} \,, v^{\ast} \right> \quad \text{ is not a inner product } \\
\mathbf{A}\mathbf{B} &= \sum_{k=0}^{2}
\left< u^{\ast} \,, v^{\ast} \right> \\
&=
\left<
\left[ \begin{array}{cc}
1 \\
3
\end{array}
\right]^{\ast}
\,,
\left[ \begin{array}{cc}
2 \\
3
\end{array}
\right]^{\ast}
\right>
+
\left<
\left[ \begin{array}{cc}
2 \\
4
\end{array}
\right]^{\ast}
\,,
\left[ \begin{array}{cc}
4 \\
5
\end{array}
\right]^{\ast}
\right> \\
&= \left[
\begin{array}{c}
1 \\
3
\end{array}
\right] \otimes \left[
\begin{array}{cc}
2 & 3
\end{array}
\right]
+
\left[
\begin{array}{c}
2 \\
4
\end{array}
\right] \otimes \left[
\begin{array}{cc}
4 & 5
\end{array}
\right] \\
&=
\begin{bmatrix}
2 & 3\\
6 & 9
\end{bmatrix}
+
\begin{bmatrix}
8 & 10\\
16 & 20
\end{bmatrix} \\
&=
\begin{bmatrix}
10 & 13\\
22 & 29
\end{bmatrix}
\end{aligned}
\end{equation}