/** * 实现矩阵的减法 * * @param other - 与指定矩阵相减的矩阵 * @return Matrix型,指定矩阵与other相减之差 * @如果矩阵的行/列数不匹配,则会抛出异常 */ public Matrix Subtract(Matrix other) { if (numColumns != other.GetNumColumns() || numRows != other.GetNumRows()) { throw new Exception("矩阵的行/列数不匹配。"); } // 构造结果矩阵 Matrix result = new Matrix(this); // 拷贝构造 // 进行减法操作 for (int i = 0; i < numRows; ++i) { for (int j = 0; j < numColumns; ++j) { result.SetElement(i, j, result.GetElement(i, j) - other.GetElement(i, j)); } } return(result); }
/** * 实现矩阵的加法 * * @param other - 与指定矩阵相加的矩阵 * @return Matrix型,指定矩阵与other相加之和 * @如果矩阵的行/列数不匹配,则会抛出异常 */ public Matrix Add(Matrix other) { // 首先检查行列数是否相等 if (numColumns != other.GetNumColumns() || numRows != other.GetNumRows()) { throw new Exception("矩阵的行/列数不匹配。"); } // 构造结果矩阵 Matrix result = new Matrix(this); // 拷贝构造 // 矩阵加法 for (int i = 0; i < numRows; ++i) { for (int j = 0; j < numColumns; ++j) { result.SetElement(i, j, result.GetElement(i, j) + other.GetElement(i, j)); } } return(result); }