?? matrixmultiply.java
字號:
public class MatrixMultiply {
public static void main(String[] argv) {
int x[][] = new int[2][3]; // 聲明二維數組x
int y[][] = { // 聲明二維數組同時進行初始化
{ 1, 4 },
{ 5, 2 },
{ 6, 3 },
};
// 為數組x的元素進行賦值
for ( int i = 0; i < 2; i++)
for( int j = 0; j < 3; j++)
x[i][j] = (i+1)*(j+3);
int result[][] = Matrix.multiply(x, y);
System.out.println("矩陣");
Matrix.printMatrix(x);
System.out.println("與矩陣");
Matrix.printMatrix(y);
System.out.println("相乘結果矩陣為");
Matrix.printMatrix(result);
} // main方法結束
} // 類MatrixMultiply結束
//聲明矩陣類
class Matrix {
public static int[][] multiply(int[][] m1, int[][] m2) {
int m1rows = m1.length; // 取m1矩陣行數
int m1cols = m1[0].length; // 取m1矩陣列數
int m2rows = m2.length; // 取m2矩陣行數
//檢查第一個矩陣的列數與第二個矩陣的行數是否相同
if (m1cols != m2rows)
throw new IllegalArgumentException("第一個矩陣的列數與第二個矩陣的行數不相同" +
",矩陣相乘無意義");
int[][] result = new int[m1rows][m2cols];
for (int i=0; i<m1rows; i++)
for (int j=0; j<m2cols; j++) {
result[i][j] = 0; //對結果數組進行初始化
// 數組m1與數組m2相乘的結果賦給數組result
for (int k = 0; k < m1cols; k++)
result[i][j] += m1[i][k] * m2[k][j];
}
return result;
} // 類MatrixMultiply結束
// 打印矩陣
public static void printMatrix(int[][] a) {
int rows = a.length;
int cols = a[0].length;
System.out.println("array["+rows+"]["+cols+"] = {");
for (int i=0; i<rows; i++) {
System.out.print("{");
for (int j=0; j<cols; j++)
if (j == cols - 1)
System.out.print(" " + a[i][j] + " ");
else
System.out.print(" " + a[i][j] + ",");
System.out.println("},");
}
System.out.println("}");
} // printMatrix方法結束
} // 類Matrix結束
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -