using System; using System.Runtime.Serialization; namespace DotNetMatrix { #region Internal Maths utility internal class Maths { /// /// sqrt(a^2 + b^2) without under/overflow. /// /// /// /// public static decimal Hypot(decimal a, decimal b) { decimal r; if (Math.Abs(a) > Math.Abs(b)) { r = b/a; r = Math.Abs(a) * (decimal)DecimalMath.Sqrt(1 + r * r); } else if (b != 0) { r = a/b; r = Math.Abs(b) * (decimal)DecimalMath.Sqrt(1 + r * r); } else { r = 0.0m; } return r; } } #endregion // Internal Maths utility /// .NET GeneralMatrix class. /// /// The .NET GeneralMatrix Class provides the fundamental operations of numerical /// linear algebra. Various constructors create Matrices from two dimensional /// arrays of decimal precision decimaling point numbers. Various "gets" and /// "sets" provide access to submatrices and matrix elements. Several methods /// implement basic matrix arithmetic, including matrix addition and /// multiplication, matrix norms, and element-by-element array operations. /// Methods for reading and printing matrices are also included. All the /// operations in this version of the GeneralMatrix Class involve real matrices. /// Complex matrices may be handled in a future version. /// /// Five fundamental matrix decompositions, which consist of pairs or triples /// of matrices, permutation vectors, and the like, produce results in five /// decomposition classes. These decompositions are accessed by the GeneralMatrix /// class to compute solutions of simultaneous linear equations, determinants, /// inverses and other matrix functions. The five decompositions are: ///

///
///
Example of use:
///

///

Solve a linear system A x = b and compute the residual norm, ||b - A x||. ///

	/// decimal[][] vals = {{1.,2.,3},{4.,5.,6.},{7.,8.,10.}};
	/// GeneralMatrix A = new GeneralMatrix(vals);
	/// GeneralMatrix b = GeneralMatrix.Random(3,1);
	/// GeneralMatrix x = A.Solve(b);
	/// GeneralMatrix r = A.Multiply(x).Subtract(b);
	/// decimal rnorm = r.NormInf();
	/// 
///
///
/// /// The MathWorks, Inc. and the National Institute of Standards and Technology. /// /// 5 August 1998 /// [Serializable] public class GeneralMatrix : System.ICloneable, System.Runtime.Serialization.ISerializable, System.IDisposable { #region Class variables /// Array for internal storage of elements. /// @serial internal array storage. /// private decimal[][] A; /// Row and column dimensions. /// @serial row dimension. /// @serial column dimension. /// private int m, n; #endregion // Class variables #region Constructors /// Construct an m-by-n matrix of zeros. /// Number of rows. /// /// Number of colums. /// public GeneralMatrix(int m, int n) { this.m = m; this.n = n; A = new decimal[m][]; for (int i = 0; i < m; i++) { A[i] = new decimal[n]; } } /// Construct an m-by-n constant matrix. /// Number of rows. /// /// Number of colums. /// /// Fill the matrix with this scalar value. /// public GeneralMatrix(int m, int n, decimal s) { this.m = m; this.n = n; A = new decimal[m][]; for (int i = 0; i < m; i++) { A[i] = new decimal[n]; } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = s; } } } /// Construct a matrix from a 2-D array. /// Two-dimensional array of decimals. /// /// All rows must have the same length /// /// /// public GeneralMatrix(decimal[][] A) { m = A.Length; n = A[0].Length; for (int i = 0; i < m; i++) { if (A[i].Length != n) { throw new System.ArgumentException("All rows must have the same length."); } } this.A = A; } /// Construct a matrix quickly without checking arguments. /// Two-dimensional array of decimals. /// /// Number of rows. /// /// Number of colums. /// public GeneralMatrix(decimal[][] A, int m, int n) { this.A = A; this.m = m; this.n = n; } /// Construct a matrix from a one-dimensional packed array /// One-dimensional array of decimals, packed by columns (ala Fortran). /// /// Number of rows. /// /// Array length must be a multiple of m. /// public GeneralMatrix(decimal[] vals, int m) { this.m = m; n = (m != 0?vals.Length / m:0); if (m * n != vals.Length) { throw new System.ArgumentException("Array length must be a multiple of m."); } A = new decimal[m][]; for (int i = 0; i < m; i++) { A[i] = new decimal[n]; } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = vals[i + j * m]; } } } #endregion // Constructors #region Public Properties /// Access the internal two-dimensional array. /// Pointer to the two-dimensional array of matrix elements. /// virtual public decimal[][] Array { get { return A; } } /// Copy the internal two-dimensional array. /// Two-dimensional array copy of matrix elements. /// virtual public decimal[][] ArrayCopy { get { decimal[][] C = new decimal[m][]; for (int i = 0; i < m; i++) { C[i] = new decimal[n]; } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = A[i][j]; } } return C; } } /// Make a one-dimensional column packed copy of the internal array. /// Matrix elements packed in a one-dimensional array by columns. /// virtual public decimal[] ColumnPackedCopy { get { decimal[] vals = new decimal[m * n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { vals[i + j * m] = A[i][j]; } } return vals; } } /// Make a one-dimensional row packed copy of the internal array. /// Matrix elements packed in a one-dimensional array by rows. /// virtual public decimal[] RowPackedCopy { get { decimal[] vals = new decimal[m * n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { vals[i * n + j] = A[i][j]; } } return vals; } } /// Get row dimension. /// m, the number of rows. /// virtual public int RowDimension { get { return m; } } /// Get column dimension. /// n, the number of columns. /// virtual public int ColumnDimension { get { return n; } } #endregion // Public Properties #region Public Methods /// Construct a matrix from a copy of a 2-D array. /// Two-dimensional array of decimals. /// /// All rows must have the same length /// public static GeneralMatrix Create(decimal[][] A) { int m = A.Length; int n = A[0].Length; GeneralMatrix X = new GeneralMatrix(m, n); decimal[][] C = X.Array; for (int i = 0; i < m; i++) { if (A[i].Length != n) { throw new System.ArgumentException("All rows must have the same length."); } for (int j = 0; j < n; j++) { C[i][j] = A[i][j]; } } return X; } /// Make a deep copy of a matrix public virtual GeneralMatrix Copy() { GeneralMatrix X = new GeneralMatrix(m, n); decimal[][] C = X.Array; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = A[i][j]; } } return X; } /// Get a single element. /// Row index. /// /// Column index. /// /// A(i,j) /// /// /// public virtual decimal GetElement(int i, int j) { return A[i][j]; } /// Get a submatrix. /// Initial row index /// /// Final row index /// /// Initial column index /// /// Final column index /// /// A(i0:i1,j0:j1) /// /// Submatrix indices /// public virtual GeneralMatrix GetMatrix(int i0, int i1, int j0, int j1) { GeneralMatrix X = new GeneralMatrix(i1 - i0 + 1, j1 - j0 + 1); decimal[][] B = X.Array; try { for (int i = i0; i <= i1; i++) { for (int j = j0; j <= j1; j++) { B[i - i0][j - j0] = A[i][j]; } } } catch (System.IndexOutOfRangeException e) { throw new System.IndexOutOfRangeException("Submatrix indices", e); } return X; } /// Get a submatrix. /// Array of row indices. /// /// Array of column indices. /// /// A(r(:),c(:)) /// /// Submatrix indices /// public virtual GeneralMatrix GetMatrix(int[] r, int[] c) { GeneralMatrix X = new GeneralMatrix(r.Length, c.Length); decimal[][] B = X.Array; try { for (int i = 0; i < r.Length; i++) { for (int j = 0; j < c.Length; j++) { B[i][j] = A[r[i]][c[j]]; } } } catch (System.IndexOutOfRangeException e) { throw new System.IndexOutOfRangeException("Submatrix indices", e); } return X; } /// Get a submatrix. /// Initial row index /// /// Final row index /// /// Array of column indices. /// /// A(i0:i1,c(:)) /// /// Submatrix indices /// public virtual GeneralMatrix GetMatrix(int i0, int i1, int[] c) { GeneralMatrix X = new GeneralMatrix(i1 - i0 + 1, c.Length); decimal[][] B = X.Array; try { for (int i = i0; i <= i1; i++) { for (int j = 0; j < c.Length; j++) { B[i - i0][j] = A[i][c[j]]; } } } catch (System.IndexOutOfRangeException e) { throw new System.IndexOutOfRangeException("Submatrix indices", e); } return X; } /// Get a submatrix. /// Array of row indices. /// /// Initial column index /// /// Final column index /// /// A(r(:),j0:j1) /// /// Submatrix indices /// public virtual GeneralMatrix GetMatrix(int[] r, int j0, int j1) { GeneralMatrix X = new GeneralMatrix(r.Length, j1 - j0 + 1); decimal[][] B = X.Array; try { for (int i = 0; i < r.Length; i++) { for (int j = j0; j <= j1; j++) { B[i][j - j0] = A[r[i]][j]; } } } catch (System.IndexOutOfRangeException e) { throw new System.IndexOutOfRangeException("Submatrix indices", e); } return X; } /// Set a single element. /// Row index. /// /// Column index. /// /// A(i,j). /// /// /// public virtual void SetElement(int i, int j, decimal s) { A[i][j] = s; } /// Set a submatrix. /// Initial row index /// /// Final row index /// /// Initial column index /// /// Final column index /// /// A(i0:i1,j0:j1) /// /// Submatrix indices /// public virtual void SetMatrix(int i0, int i1, int j0, int j1, GeneralMatrix X) { try { for (int i = i0; i <= i1; i++) { for (int j = j0; j <= j1; j++) { A[i][j] = X.GetElement(i - i0, j - j0); } } } catch (System.IndexOutOfRangeException e) { throw new System.IndexOutOfRangeException("Submatrix indices", e); } } /// Set a submatrix. /// Array of row indices. /// /// Array of column indices. /// /// A(r(:),c(:)) /// /// Submatrix indices /// public virtual void SetMatrix(int[] r, int[] c, GeneralMatrix X) { try { for (int i = 0; i < r.Length; i++) { for (int j = 0; j < c.Length; j++) { A[r[i]][c[j]] = X.GetElement(i, j); } } } catch (System.IndexOutOfRangeException e) { throw new System.IndexOutOfRangeException("Submatrix indices", e); } } /// Set a submatrix. /// Array of row indices. /// /// Initial column index /// /// Final column index /// /// A(r(:),j0:j1) /// /// Submatrix indices /// public virtual void SetMatrix(int[] r, int j0, int j1, GeneralMatrix X) { try { for (int i = 0; i < r.Length; i++) { for (int j = j0; j <= j1; j++) { A[r[i]][j] = X.GetElement(i, j - j0); } } } catch (System.IndexOutOfRangeException e) { throw new System.IndexOutOfRangeException("Submatrix indices", e); } } /// Set a submatrix. /// Initial row index /// /// Final row index /// /// Array of column indices. /// /// A(i0:i1,c(:)) /// /// Submatrix indices /// public virtual void SetMatrix(int i0, int i1, int[] c, GeneralMatrix X) { try { for (int i = i0; i <= i1; i++) { for (int j = 0; j < c.Length; j++) { A[i][c[j]] = X.GetElement(i - i0, j); } } } catch (System.IndexOutOfRangeException e) { throw new System.IndexOutOfRangeException("Submatrix indices", e); } } /// Matrix transpose. /// A' /// public virtual GeneralMatrix Transpose() { GeneralMatrix X = new GeneralMatrix(n, m); decimal[][] C = X.Array; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[j][i] = A[i][j]; } } return X; } /// One norm /// maximum column sum. /// public virtual decimal Norm1() { decimal f = 0; for (int j = 0; j < n; j++) { decimal s = 0; for (int i = 0; i < m; i++) { s += System.Math.Abs(A[i][j]); } f = System.Math.Max(f, s); } return f; } /// Two norm /// maximum singular value. /// public virtual decimal Norm2() { return (new SingularValueDecomposition(this).Norm2()); } /// Infinity norm /// maximum row sum. /// public virtual decimal NormInf() { decimal f = 0; for (int i = 0; i < m; i++) { decimal s = 0; for (int j = 0; j < n; j++) { s += System.Math.Abs(A[i][j]); } f = System.Math.Max(f, s); } return f; } /// Frobenius norm /// sqrt of sum of squares of all elements. /// public virtual decimal NormF() { decimal f = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { f = Maths.Hypot(f, A[i][j]); } } return f; } /// Unary minus /// -A /// public virtual GeneralMatrix UnaryMinus() { GeneralMatrix X = new GeneralMatrix(m, n); decimal[][] C = X.Array; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = -A[i][j]; } } return X; } /// C = A + B /// another matrix /// /// A + B /// public virtual GeneralMatrix Add(GeneralMatrix B) { CheckMatrixDimensions(B); GeneralMatrix X = new GeneralMatrix(m, n); decimal[][] C = X.Array; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = A[i][j] + B.A[i][j]; } } return X; } /// A = A + B /// another matrix /// /// A + B /// public virtual GeneralMatrix AddEquals(GeneralMatrix B) { CheckMatrixDimensions(B); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = A[i][j] + B.A[i][j]; } } return this; } /// C = A - B /// another matrix /// /// A - B /// public virtual GeneralMatrix Subtract(GeneralMatrix B) { CheckMatrixDimensions(B); GeneralMatrix X = new GeneralMatrix(m, n); decimal[][] C = X.Array; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = A[i][j] - B.A[i][j]; } } return X; } /// A = A - B /// another matrix /// /// A - B /// public virtual GeneralMatrix SubtractEquals(GeneralMatrix B) { CheckMatrixDimensions(B); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = A[i][j] - B.A[i][j]; } } return this; } /// Element-by-element multiplication, C = A.*B /// another matrix /// /// A.*B /// public virtual GeneralMatrix ArrayMultiply(GeneralMatrix B) { CheckMatrixDimensions(B); GeneralMatrix X = new GeneralMatrix(m, n); decimal[][] C = X.Array; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = A[i][j] * B.A[i][j]; } } return X; } /// Element-by-element multiplication in place, A = A.*B /// another matrix /// /// A.*B /// public virtual GeneralMatrix ArrayMultiplyEquals(GeneralMatrix B) { CheckMatrixDimensions(B); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = A[i][j] * B.A[i][j]; } } return this; } /// Element-by-element right division, C = A./B /// another matrix /// /// A./B /// public virtual GeneralMatrix ArrayRightDivide(GeneralMatrix B) { CheckMatrixDimensions(B); GeneralMatrix X = new GeneralMatrix(m, n); decimal[][] C = X.Array; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = A[i][j] / B.A[i][j]; } } return X; } /// Element-by-element right division in place, A = A./B /// another matrix /// /// A./B /// public virtual GeneralMatrix ArrayRightDivideEquals(GeneralMatrix B) { CheckMatrixDimensions(B); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = A[i][j] / B.A[i][j]; } } return this; } /// Element-by-element left division, C = A.\B /// another matrix /// /// A.\B /// public virtual GeneralMatrix ArrayLeftDivide(GeneralMatrix B) { CheckMatrixDimensions(B); GeneralMatrix X = new GeneralMatrix(m, n); decimal[][] C = X.Array; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = B.A[i][j] / A[i][j]; } } return X; } /// Element-by-element left division in place, A = A.\B /// another matrix /// /// A.\B /// public virtual GeneralMatrix ArrayLeftDivideEquals(GeneralMatrix B) { CheckMatrixDimensions(B); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = B.A[i][j] / A[i][j]; } } return this; } /// Multiply a matrix by a scalar, C = s*A /// scalar /// /// s*A /// public virtual GeneralMatrix Multiply(decimal s) { GeneralMatrix X = new GeneralMatrix(m, n); decimal[][] C = X.Array; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = s * A[i][j]; } } return X; } /// Multiply a matrix by a scalar in place, A = s*A /// scalar /// /// replace A by s*A /// public virtual GeneralMatrix MultiplyEquals(decimal s) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = s * A[i][j]; } } return this; } /// Linear algebraic matrix multiplication, A * B /// another matrix /// /// Matrix product, A * B /// /// Matrix inner dimensions must agree. /// public virtual GeneralMatrix Multiply(GeneralMatrix B) { if (B.m != n) { throw new System.ArgumentException("GeneralMatrix inner dimensions must agree."); } GeneralMatrix X = new GeneralMatrix(m, B.n); decimal[][] C = X.Array; decimal[] Bcolj = new decimal[n]; for (int j = 0; j < B.n; j++) { for (int k = 0; k < n; k++) { Bcolj[k] = B.A[k][j]; } for (int i = 0; i < m; i++) { decimal[] Arowi = A[i]; decimal s = 0; for (int k = 0; k < n; k++) { s += Arowi[k] * Bcolj[k]; } C[i][j] = s; } } return X; } #region Operator Overloading /// /// Addition of matrices /// /// /// /// public static GeneralMatrix operator +(GeneralMatrix m1, GeneralMatrix m2) { return m1.Add(m2); } /// /// Subtraction of matrices /// /// /// /// public static GeneralMatrix operator -(GeneralMatrix m1, GeneralMatrix m2) { return m1.Subtract(m2); } /// /// Multiplication of matrices /// /// /// /// public static GeneralMatrix operator *(GeneralMatrix m1, GeneralMatrix m2) { return m1.Multiply(m2); } #endregion //Operator Overloading /// LU Decomposition /// LUDecomposition /// /// /// public virtual LUDecomposition LUD() { return new LUDecomposition(this); } /// QR Decomposition /// QRDecomposition /// /// /// public virtual QRDecomposition QRD() { return new QRDecomposition(this); } /// Cholesky Decomposition /// CholeskyDecomposition /// /// /// public virtual CholeskyDecomposition chol() { return new CholeskyDecomposition(this); } /// Singular Value Decomposition /// SingularValueDecomposition /// /// /// public virtual SingularValueDecomposition SVD() { return new SingularValueDecomposition(this); } /// Eigenvalue Decomposition /// EigenvalueDecomposition /// /// /// public virtual EigenvalueDecomposition Eigen() { return new EigenvalueDecomposition(this); } /// Solve A*X = B /// right hand side /// /// solution if A is square, least squares solution otherwise /// public virtual GeneralMatrix Solve(GeneralMatrix B) { return (m == n ? (new LUDecomposition(this)).Solve(B):(new QRDecomposition(this)).Solve(B)); } /// Solve X*A = B, which is also A'*X' = B' /// right hand side /// /// solution if A is square, least squares solution otherwise. /// public virtual GeneralMatrix SolveTranspose(GeneralMatrix B) { return Transpose().Solve(B.Transpose()); } /// Matrix inverse or pseudoinverse /// inverse(A) if A is square, pseudoinverse otherwise. /// public virtual GeneralMatrix Inverse() { return Solve(Identity(m, m)); } /// GeneralMatrix determinant /// determinant /// public virtual decimal Determinant() { return new LUDecomposition(this).Determinant(); } /// GeneralMatrix rank /// effective numerical rank, obtained from SVD. /// public virtual int Rank() { return new SingularValueDecomposition(this).Rank(); } /// Matrix condition (2 norm) /// ratio of largest to smallest singular value. /// public virtual decimal Condition() { return new SingularValueDecomposition(this).Condition(); } /// Matrix trace. /// sum of the diagonal elements. /// public virtual decimal Trace() { decimal t = 0; for (int i = 0; i < System.Math.Min(m, n); i++) { t += A[i][i]; } return t; } /// Generate matrix with random elements /// Number of rows. /// /// Number of colums. /// /// An m-by-n matrix with uniformly distributed random elements. /// /*public static GeneralMatrix Random(int m, int n) { System.Random random = new System.Random(); GeneralMatrix A = new GeneralMatrix(m, n); decimal[][] X = A.Array; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { X[i][j] = random.Nextdecimal(); } } return A; }*/ /// Generate identity matrix /// Number of rows. /// /// Number of colums. /// /// An m-by-n matrix with ones on the diagonal and zeros elsewhere. /// public static GeneralMatrix Identity(int m, int n) { GeneralMatrix A = new GeneralMatrix(m, n); decimal[][] X = A.Array; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { X[i][j] = (i == j ? 1.0m : 0.0m); } } return A; } #endregion // Public Methods #region Private Methods /// Check if size(A) == size(B) * private void CheckMatrixDimensions(GeneralMatrix B) { if (B.m != m || B.n != n) { throw new System.ArgumentException("GeneralMatrix dimensions must agree."); } } #endregion // Private Methods #region Implement IDisposable /// /// Do not make this method virtual. /// A derived class should not be able to override this method. /// public void Dispose() { Dispose(true); } /// /// Dispose(bool disposing) executes in two distinct scenarios. /// If disposing equals true, the method has been called directly /// or indirectly by a user's code. Managed and unmanaged resources /// can be disposed. /// If disposing equals false, the method has been called by the /// runtime from inside the finalizer and you should not reference /// other objects. Only unmanaged resources can be disposed. /// /// private void Dispose(bool disposing) { // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. if (disposing) GC.SuppressFinalize(this); } /// /// This destructor will run only if the Dispose method /// does not get called. /// It gives your base class the opportunity to finalize. /// Do not provide destructors in types derived from this class. /// ~GeneralMatrix() { // Do not re-create Dispose clean-up code here. // Calling Dispose(false) is optimal in terms of // readability and maintainability. Dispose(false); } #endregion // Implement IDisposable /// Clone the GeneralMatrix object. public System.Object Clone() { return this.Copy(); } /// /// A method called when serializing this class /// /// /// void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { } } }