Skip to content

Instantly share code, notes, and snippets.

@HabaCo
Last active August 29, 2015 14:01
Show Gist options
  • Save HabaCo/c6ae3b69f518a1d92a2c to your computer and use it in GitHub Desktop.
Save HabaCo/c6ae3b69f518a1d92a2c to your computer and use it in GitHub Desktop.
矩陣相乘
package exam;
/* ========== 矩陣相乘 ========== */
public class Homework1 {
public static void main(String[] args) {
/**------------------------------------------------------------------
eg.座標對照
A B
┌ [0][0] [0][1] ┐ ┌ [0][0] [0][1] [0][2] ┐
│ [1][0] [1][1] │ X └ [1][0] [1][1] [1][2] ┘
└ [2][0] [2][1] ┘
C1
┌ A[0][0]*B[0][0] A[0][0]*B[0][1] A[0][0]*B[0][2] ┐
= │ A[1][0]*B[0][0] A[1][0]*B[0][1] A[1][0]*B[0][2] │
└ A[2][0]*B[0][0] A[2][0]*B[0][1] A[2][0]*B[0][2] ┘
C2
┌ A[0][1]*B[1][0] A[0][1]*B[1][1] A[0][1]*B[1][2] ┐
+ │ A[1][1]*B[1][0] A[1][1]*B[1][1] A[1][1]*B[1][2] │
└ A[2][1]*B[1][0] A[2][1]*B[1][1] A[2][1]*B[1][2] ┘
A B C
┌ A B ┐ ┌ m n o ┐ ┌ Am+Bp An+Bq Ao+Br ┐
│ C D │ X └ p q r ┘ = │ Cm+Dp Cn+Dq Co+Dr │
└ E F ┘ └ Em+Fp En+Fq Eo+Fr ┘
C1 C2
將矩陣拆開可得 ┌ Am An Ao ┐ ┌ Bp Bq Br ┐
│ Cm Cn Co │ + │ Dp Dq Dr │
└ Em En Eo ┘ └ Fp Fq Fr ┘
方法 :
經由C1,C2可得知 A與m,n,o相乘 B與p,q,r相乘
C與m,n,o相乘 D與p,q,r相乘
E與m,n,o相乘 F與p,q,r相乘
因為在給予矩陣值時順序習慣由左至右,由上至下,所以在這裡會是
C第1列=C1的第1列+C2第1列
C第2列=C1的第2列+C2第2列
C第3列=C1的第3列+C2第3列
┌────── 發現【列】可以用一個迴圈 (i)控制,並且範圍將在A矩陣的第一列 (矩陣相乘之規則)
│ then 深入探討
│ C1的第1列+C2第1列=C第1列,且A與m,n,o相乘 B與p,q,r相乘
│ A[0][0]與m[0][0],n[0][1],o[0][2]相乘 B[0][1]與p[1][0],q[1][1],r[1][2]相乘
│ *可以得知A的【列】和m,n,o的【列】一樣 B的【行】和p,q,r的【列】一樣 ┐
│ *且 A 與 B 的關係為行+1 ; m,n,o的關係為行+1 ; p,q,r的關係為行+1 │
│ (1)先完成 A with m,n,o │
│ i=0 │
│ for(j=0,1,2) │
│ A[0][i]*B[i][j <───────┬───────────────────────────────┘
│ (2)再完成 B with p,q,r │
│ i=1 │
│ for(j=0,1,2) │
│ A[0][i]*B[i][j] <───────┘
│ 結合 (1)+(2) 可得
│ for(i=0 to 1)
│ for(j=0 to 2)
│ A[0][i]*B[i][j]
│ ==> C第一列完成
└──>(3) for(k=0 to 3)
for(i=0 to 1)
for(j=0 to 2)
C=A[k][i]*B[i][j]
※使該公式可套用任意矩陣相乘 (符合公式規定之矩陣)
1.k之範圍為0~3是因為新的C矩陣有3列,又C矩陣的列=A矩陣的列:
k=A->row
2.i之範圍為0~1是因為切割成C1與C2(A與B之乘積)相加,可得知A行數(=B列數)個數決定C矩陣切割之個數:
i=A->col
3.j之範圍為0~2是因為A須與B的行數列做乘積,可得知B矩陣單一行數個數決定j之範圍:
j=B->col
-------------------------------------------------------------------------------------------- */
int[][] arr1 = {{1,2}, /* 3x2 ┌ 1 2 ┐ */
{2,3}, /* matrix | 2 3 | */
{4,2}}; /* └ 4 2 ┘ */
int[][] arr2 = {{2,1,2}, /* 2x3 ┌ 2 1 2 ┐ */
{3,2,5}}; /* matrix └ 3 2 5 ┘ */
// 利用第一個矩陣的row定義新矩陣的row
int multiRow = arr1.length;
// 利用第二個矩陣的col定義新矩陣的col
int multiCol = arr2[0].length;
int[][] multi = new int[multiRow][multiCol];
for (int k=0; k<arr1.length; k++)
for (int i=0; i<arr2.length; i++)
for (int j=0; j<arr2[0].length; j++)
multi[k][j]+= arr1[k][i]*arr2[i][j];
for (int i=0; i<multiRow; i++){
for (int j=0; j<multiCol; j++){
System.out.print(multi[i][j] + " ");
if (multi[i][j] < 10)System.out.print(" ");
}
System.out.println();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment