static void Main(string[] args) { IMatrix A = new SparseMatrix(2, 3); IMatrix B = new SparseMatrix(3, 2); IMatrix C = new SparseMatrix(2, 2); A[0, 2] = 1; A[1, 0] = 1; B[1, 1] = 4; B[2, 0] = 1; C[0, 1] = 1; C[1, 0] = 1; IMatrix D = (SparseMatrix)A * (SparseMatrix)B + (SparseMatrix)C; IMatrix E = A.Multiply(B).Add(C); Console.WriteLine("D:\n{0}", D); Console.WriteLine("E:\n{0}", E); }
/// <summary> /// 矩阵转置 /// </summary> /// <returns>转置后的新矩阵</returns> public IMatrix Transpose() { SparseMatrix temp = new SparseMatrix(cols, rows); for (int i = 0; i < temp.Rows; i++) for (int j = 0; j < temp.Cols; j++) temp[i, j] = this[j, i]; return temp; }
/// <summary> /// 矩阵乘法 /// </summary> /// <param name="B">与之右乘的另一个矩阵</param> /// <returns>相乘后的新矩阵</returns> public IMatrix Multiply(IMatrix B) { if (B == null) throw new Exception("参数矩阵为null."); if (cols != B.Rows) throw new Exception("两矩阵不能相乘."); SparseMatrix temp = new SparseMatrix(rows, B.Cols); for (int i = 0; i < rows; i++) { for (int j = 0; j < B.Cols; j++) { for (int k = 0; k < cols; k++) temp[i, j] += this[i, k] * B[k, j]; } } return temp; }
/// <summary> /// 矩阵加法 /// </summary> /// <param name="B">与之相加的另一个矩阵</param> /// <returns>相加后的新矩阵</returns> public IMatrix Add(IMatrix B) { if (B == null) throw new Exception("参数矩阵为null."); if (B.Rows != this.rows || B.Cols != this.cols) throw new Exception("两矩阵不能相加."); SparseMatrix temp = new SparseMatrix(rows, cols); for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) temp[i, j] = this[i, j] + B[i, j]; return temp; }