DAY31 整数矩阵及其运算
本次代码通过IntMatrix类封装了二维整数矩阵的核心操作,思路如下:数据封装→基础操作(修改和获取元素、获取维度,toString返回字符串表示,getData返回内部数组引用)→矩阵运算(实现矩阵加法和乘法)→功能演示(main方法)证类的功能。
1.声明变量
声明了一个名为data的变量,其类型是int[][],表示这是一个二维整数数组
此处仅声明变量,未初始化
/**
* The data.
*/
int[][] data;
2.初始化一个整数矩阵(第一个构造方法)
这个构造方法的作用是根据指定的行数和列数,初始化矩阵的存储空间。
接收两个int类型参数:paraRows(行数)和paraColumns(列数)
/**
*********************
* The first constructor.
*
* @param paraRows
* The number of rows.
* @param paraColumns
* The number of columns.
*********************
*/
public IntMatrix(int paraRows, int paraColumns) {
data = new int[paraRows][paraColumns];
}// Of the first constructor
3.创建给定矩阵的副本(第二个构造方法)
通过一个已有的二维整数数组创建一个新的IntMatrix对象(实现矩阵的复制功能)
/**
*********************
* The second constructor. Construct a copy of the given matrix.
*
* @param paraMatrix
* The given matrix.
*********************
*/
public IntMatrix(int[][] paraMatrix) {
data = new int[paraMatrix.length][paraMatrix[0].length];
// Copy elements.
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[0].length; j++) {
data[i][j] = paraMatrix[i][j];
} // Of for j
} // Of for i
}// Of the second constructor
4.创建给定矩阵的副本(第三个构造方法)
这行代码实际是调用了当前类的第二个构造方法(接收int[][]参数的那个),将已有IntMatrix对象的内部数据数组作为参数传入
这种通过this()调用其他构造方法的方式称为构造方法重载复用,避免了代码重复,提高了代码的可维护性
/**
*********************
* The third constructor. Construct a copy of the given matrix.
*
* @param paraMatrix
* The given matrix.
*********************
*/
public IntMatrix(IntMatrix paraMatrix) {
this(paraMatrix.getData());
}// Of the third constructor
5.getIdentityMatrix方法获取单位矩阵
①IntMatrix resultMatrix = new IntMatrix(paraRows, paraRows);
创建一个新的IntMatrix对象,行数和列数都是paraRows(即创建一个方阵)
此时矩阵中所有元素默认值为 0(因为int类型数组的默认值是 0)
②通过循环设置对角线元素为 1
循环变量i同时表示行索引和列索引
将矩阵中(i,i)位置的元素(即主对角线上的元素)设置为 1
注释提到 “根据访问控制,resultMatrix.data 可以被直接访问”,说明data成员变量的访问权限允许在类内部直接操作
③return resultMatrix;返回创建好的单位矩阵对象
/**
*********************
* Get identity matrix. The values at the diagonal are all 1.
*
* @param paraRows
* The given rows.
*********************
*/
public static IntMatrix getIdentityMatrix(int paraRows) {
IntMatrix resultMatrix = new IntMatrix(paraRows, paraRows);
for (int i = 0; i < paraRows; i++) {
// According to access control, resultMatrix.data can be visited
// directly.
resultMatrix.data[i][i] = 1;
} // Of for i
return resultMatrix;
}// Of getIdentityMatrix
6.字符串表示以及获取内部数据
重写toString()方法,用于返回矩阵的字符串表示形式
返回类中存储矩阵数据的二维数组data的引用,用于外部获取矩阵的原始数据。
/**
*********************
* Overrides the method claimed in Object, the superclass of any class.
*********************
*/
public String toString() {
return Arrays.deepToString(data);
}// Of toString
/**
*********************
* Get my data. Warning, the reference to the data instead of a copy of the
* data is returned.
*
* @return The data matrix.
*********************
*/
public int[][] getData() {
return data;
}// Of getData
7.getRows() 方法获取矩阵行数
二维数组data的length属性表示数组的行数(即第一维的长度)。
因此直接返回data.length即可得到矩阵的行数。
/**
*********************
* Getter.
*
* @return The number of rows.
*********************
*/
public int getRows() {
return data.length;
}// Of getRows
8.getColumns() 方法获取矩阵列数
二维数组中,data[0]表示第一行的数组,其length属性即为该行的元素个数,也就是矩阵的列数(假设矩阵是规则的,即每行的列数相同)。
因此返回data[0].length可得到矩阵的列数。
/**
*********************
* Getter.
*
* @return The number of columns.
*********************
*/
public int getColumns() {
return data[0].length;
}// Of getColumns
9.设置和获取矩阵元素值
setValue() 方法设置矩阵中指定位置(行、列)的元素值。
参数说明:
paraRow:元素所在的行索引(从 0 开始)
paraColumn:元素所在的列索引(从 0 开始)
paraValue:要设置的新值(整数类型)
/**
*********************
* Set one the value of one element.
*
* @param paraRow
* The row of the element.
* @param paraColumn
* The column of the element.
* @param paraValue
* The new value.
*********************
*/
public void setValue(int paraRow, int paraColumn, int paraValue) {
data[paraRow][paraColumn] = paraValue;
}// Of setValue
getValue() 方法获取矩阵中指定位置(行、列)的元素值。
参数说明:
paraRow:元素所在的行索引(从 0 开始)
paraColumn:元素所在的列索引(从 0 开始)
返回值:指定位置的元素值(整数类型)。
实现逻辑:通过二维数组的索引访问data[paraRow][paraColumn],并返回该位置的元素值。
/**
*********************
* Get the value of one element.
*
* @param paraRow
* The row of the element.
* @param paraColumn
* The column of the element.
*********************
*/
public int getValue(int paraRow, int paraColumn) {
return data[paraRow][paraColumn];
}// Of getValue
10.add方法
用于将另一个矩阵与当前矩阵进行加法运算,并将结果存储在当前矩阵中。
步骤 1:获取传入矩阵的数据
通过paraMatrix.getData()获取传入矩阵的内部二维数组tempData(注意:这里获取的是引用,而非副本)。
// Step 1. Get the data of the given matrix.
int[][] tempData = paraMatrix.getData();
步骤 2:校验矩阵尺寸(核心前提)
矩阵加法的数学规则:只有行数和列数完全相同的两个矩阵才能相加。
代码通过两个if判断:
若当前矩阵的行数(data.length)与传入矩阵的行数(tempData.length)不相等,抛出异常。
若当前矩阵的列数(data[0].length)与传入矩阵的列数(tempData[0].length)不相等,抛出异常。
异常信息明确提示不匹配的维度,便于调试。
// Step 2. Size check.
if (data.length != tempData.length) {
throw new Exception("Cannot add matrices. Rows not match: " + data.length + " vs. "
+ tempData.length + ".");
} // Of if
if (data[0].length != tempData[0].length) {
throw new Exception("Cannot add matrices. Rows not match: " + data[0].length + " vs. "
+ tempData[0].length + ".");
} // Of if
步骤 3:执行加法运算
通过双重循环遍历两个矩阵的每个元素:
外层循环i遍历行索引,内层循环j遍历列索引。
执行data[i][j] += tempData[i][j],即当前矩阵的元素加上传入矩阵对应位置的元素,结果存回当前矩阵。
运算规则符合矩阵加法的定义:两个矩阵对应位置的元素相加。
// Step 3. Add to me.
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[0].length; j++) {
data[i][j] += tempData[i][j];
} // Of for j
} // Of for i
11.静态add方法
用于对两个已存在的矩阵进行加法运算,并返回一个新的矩阵作为结果(不修改原矩阵)。
步骤 1:克隆第一个矩阵
IntMatrix resultMatrix = new IntMatrix(paraMatrix1);:通过IntMatrix的第三个构造方法,创建paraMatrix1的副本作为结果矩阵的初始值。
这一步确保原矩阵paraMatrix1不会被修改(与实例方法add的 “修改自身” 行为不同)。
// Step 1. Clone the first matrix.
IntMatrix resultMatrix = new IntMatrix(paraMatrix1);
步骤 2:执行矩阵加法
resultMatrix.add(paraMatrix2);:调用实例方法add,将paraMatrix2的元素加到resultMatrix中。
这里复用了之前实现的实例add方法的逻辑,包括尺寸校验和元素相加,避免代码重复。
// Step 2. Add the second one.
resultMatrix.add(paraMatrix2);
return resultMatrix;
12.静态multiply方法
用于实现两个矩阵的乘法运算,并返回一个新的矩阵作为结果
方法定义与参数
public static IntMatrix multiply(…):静态方法,可通过类名直接调用,返回一个新的IntMatrix对象(乘法结果)。
参数paraMatrix1和paraMatrix2:分别表示要相乘的两个矩阵(左矩阵和右矩阵)。
throws Exception:声明可能抛出异常(当矩阵尺寸不满足乘法条件时)。
步骤 1:校验矩阵乘法的尺寸条件
由于矩阵乘法的数学规则:左矩阵的列数必须等于右矩阵的行数,否则无法相乘。
代码通过if (tempData1[0].length != tempData2.length)判断:
tempData1[0].length是左矩阵的列数
tempData2.length是右矩阵的行数
若不满足条件,抛出异常并提示不匹配的维度。
步骤 2:为结果矩阵分配空间
矩阵乘法的结果矩阵行数 = 左矩阵的行数,列数 = 右矩阵的列数。
因此创建int[][] resultData = new int[tempData1.length][tempData2[0].length],其中:
tempData1.length是左矩阵的行数(结果矩阵的行数)
tempData2[0].length是右矩阵的列数(结果矩阵的列数)
步骤 3:执行矩阵乘法运算(核心逻辑)
通过三重循环实现矩阵乘法:
外层循环i:遍历结果矩阵的行(对应左矩阵的行)
中层循环j:遍历结果矩阵的列(对应右矩阵的列)
内层循环k:计算结果矩阵(i,j)位置的元素值,公式为:
resultData[i][j] = sum(左矩阵[i][k] * 右矩阵[k][j]),其中k从0到左矩阵列数-1
符合矩阵乘法的数学定义:结果矩阵的每个元素是左矩阵对应行与右矩阵对应列的元素乘积之和。
步骤 4:返回结果矩阵
通过new IntMatrix(resultData)创建结果矩阵对象并返回,原矩阵paraMatrix1和paraMatrix2的数据不会被修改。
/**
*********************
* Multiply two existing matrices.
*
* @param paraMatrix1
* The first matrix.
* @param paraMatrix2
* The second matrix.
* @return A new matrix.
*********************
*/
public static IntMatrix multiply(IntMatrix paraMatrix1, IntMatrix paraMatrix2)
throws Exception {
// Step 1. Check size.
int[][] tempData1 = paraMatrix1.getData();
int[][] tempData2 = paraMatrix2.getData();
if (tempData1[0].length != tempData2.length) {
throw new Exception("Cannot multiply matrices: " + tempData1[0].length + " vs. "
+ tempData2.length + ".");
} // Of if
// Step 2. Allocate space.
int[][] resultData = new int[tempData1.length][tempData2[0].length];
// Step 3. Multiply.
for (int i = 0; i < tempData1.length; i++) {
for (int j = 0; j < tempData2[0].length; j++) {
for (int k = 0; k < tempData1[0].length; k++) {
resultData[i][j] += tempData1[i][k] * tempData2[k][j];
} // Of for k
} // Of for j
} // Of for i
// Step 4. Construct the matrix object.
IntMatrix resultMatrix = new IntMatrix(resultData);
return resultMatrix;
}// Of multiply
13.main方法
作为程序的入口点,演示矩阵的创建、修改、乘法和加法等操作
/**
*********************
* The entrance of the program.
*
* @param args
* Not used now.
*********************
*/
public static void main(String args[]) {
IntMatrix tempMatrix1 = new IntMatrix(3, 3);
tempMatrix1.setValue(0, 1, 1);
tempMatrix1.setValue(1, 0, 1);
tempMatrix1.setValue(1, 2, 1);
tempMatrix1.setValue(2, 1, 1);
System.out.println("The original matrix is: " + tempMatrix1);
IntMatrix tempMatrix2 = null;
try {
tempMatrix2 = IntMatrix.multiply(tempMatrix1, tempMatrix1);
} catch (Exception ee) {
System.out.println(ee);
} // Of try
System.out.println("The square matrix is: " + tempMatrix2);
IntMatrix tempMatrix3 = new IntMatrix(tempMatrix2);
try {
tempMatrix3.add(tempMatrix1);
} catch (Exception ee) {
System.out.println(ee);
} // Of try
System.out.println("The connectivity matrix is: " + tempMatrix3);
}// Of main