// // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // Copyright (c) 2009-2010 Math.NET // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // namespace MathNet.Numerics.LinearAlgebra.Generic { using System; using System.Collections.Generic; using System.Numerics; using System.Text; using Factorization; using Numerics; using Properties; using Threading; /// /// Defines the base class for Matrix classes. /// /// Supported data types are double, single, , and . [Serializable] public abstract partial class Matrix : #if SILVERLIGHT IFormattable, IEquatable> #else IFormattable, IEquatable>, ICloneable #endif where T : struct, IEquatable, IFormattable { /// /// Initializes a new instance of the Matrix class. /// /// /// The number of rows. /// /// /// The number of columns. /// protected Matrix(int rows, int columns) { if (rows <= 0) { throw new ArgumentOutOfRangeException(Resources.MatrixRowsMustBePositive); } if (columns <= 0) { throw new ArgumentOutOfRangeException(Resources.MatrixColumnsMustBePositive); } RowCount = rows; ColumnCount = columns; } /// /// Initializes a new instance of the Matrix class. /// /// /// The order of the matrix. /// protected Matrix(int order) { if (order <= 0) { throw new ArgumentOutOfRangeException(Resources.MatrixRowsOrColumnsMustBePositive); } RowCount = order; ColumnCount = order; } /// /// Gets the number of columns. /// /// The number of columns. public virtual int ColumnCount { get; private set; } /// /// Gets the number of rows. /// /// The number of rows. public virtual int RowCount { get; private set; } /// /// Gets or sets the value at the given row and column. /// /// /// The row of the element. /// /// /// The column of the element. /// /// The value to get or set. /// This method is ranged checked. and /// to get and set values without range checking. public virtual T this[int row, int column] { get { RangeCheck(row, column); return At(row, column); } set { RangeCheck(row, column); At(row, column, value); } } /// /// Retrieves the requested element without range checking. /// /// /// The row of the element. /// /// /// The column of the element. /// /// /// The requested element. /// public abstract T At(int row, int column); /// /// Sets the value of the given element. /// /// /// The row of the element. /// /// /// The column of the element. /// /// /// The value to set the element to. /// public abstract void At(int row, int column, T value); /// /// Creates a clone of this instance. /// /// /// A clone of the instance. /// public virtual Matrix Clone() { var result = CreateMatrix(RowCount, ColumnCount); CopyTo(result); return result; } /// /// Copies the elements of this matrix to the given matrix. /// /// /// The matrix to copy values into. /// /// /// If target is . /// /// /// If this and the target matrix do not have the same dimensions.. /// public virtual void CopyTo(Matrix target) { if (target == null) { throw new ArgumentNullException("target"); } if (ReferenceEquals(this, target)) { return; } if (RowCount != target.RowCount || ColumnCount != target.ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixDimensions, "target"); } for (var i = 0; i < RowCount; i++) { for (var j = 0; j < ColumnCount; j++) { target.At(i, j, At(i, j)); } } } /// /// Creates a Matrix for the given number of rows and columns. /// /// /// The number of rows. /// /// /// The number of columns. /// /// /// A Matrix with the given dimensions. /// /// /// Creates a matrix of the same matrix type as the current matrix. /// public abstract Matrix CreateMatrix(int numberOfRows, int numberOfColumns); /// /// Creates a Vector with a the given dimension. /// /// The size of the vector. /// /// A Vector with the given dimension. /// /// /// Creates a vector of the same type as the current matrix. /// public abstract Vector CreateVector(int size); /// /// Returns a that represents this instance. /// /// /// A that represents this instance. /// public override string ToString() { return ToString(null, null); } /// /// Copies a row into an Vector. /// /// The row to copy. /// A Vector containing the copied elements. /// If is negative, /// or greater than or equal to the number of rows. public virtual Vector Row(int index) { var ret = CreateVector(ColumnCount); Row(index, 0, ColumnCount, ret); return ret; } /// /// Copies a row into to the given Vector. /// /// The row to copy. /// The Vector to copy the row into. /// If the result vector is . /// If is negative, /// or greater than or equal to the number of rows. /// If this.Columns != result.Count. public virtual void Row(int index, Vector result) { Row(index, 0, ColumnCount, result); } /// /// Copies the requested row elements into a new Vector. /// /// The row to copy elements from. /// The column to start copying from. /// The number of elements to copy. /// A Vector containing the requested elements. /// If: /// is negative, /// or greater than or equal to the number of rows. /// is negative, /// or greater than or equal to the number of columns. /// (columnIndex + length) >= Columns. /// If is not positive. public virtual Vector Row(int rowIndex, int columnIndex, int length) { var ret = CreateVector(length); Row(rowIndex, columnIndex, length, ret); return ret; } /// /// Copies the requested row elements into a new Vector. /// /// The row to copy elements from. /// The column to start copying from. /// The number of elements to copy. /// The Vector to copy the column into. /// If the result Vector is . /// If is negative, /// or greater than or equal to the number of columns. /// If is negative, /// or greater than or equal to the number of rows. /// If + /// is greater than or equal to the number of rows. /// If is not positive. /// If result.Count < length. public virtual void Row(int rowIndex, int columnIndex, int length, Vector result) { if (result == null) { throw new ArgumentNullException("result"); } if (rowIndex >= RowCount || rowIndex < 0) { throw new ArgumentOutOfRangeException("rowIndex"); } if (columnIndex >= ColumnCount || columnIndex < 0) { throw new ArgumentOutOfRangeException("columnIndex"); } if (columnIndex + length > ColumnCount) { throw new ArgumentOutOfRangeException("length"); } if (length < 1) { throw new ArgumentException(Resources.ArgumentMustBePositive, "length"); } if (result.Count < length) { throw new ArgumentException(Resources.ArgumentVectorsSameLength, "result"); } for (int i = columnIndex, j = 0; i < columnIndex + length; i++, j++) { result[j] = At(rowIndex, i); } } /// /// Copies a column into a new Vector>. /// /// The column to copy. /// A Vector containing the copied elements. /// If is negative, /// or greater than or equal to the number of columns. public virtual Vector Column(int index) { var result = CreateVector(RowCount); Column(index, 0, RowCount, result); return result; } /// /// Copies a column into to the given Vector. /// /// The column to copy. /// The Vector to copy the column into. /// If the result Vector is . /// If is negative, /// or greater than or equal to the number of columns. /// If this.Rows != result.Count. public virtual void Column(int index, Vector result) { Column(index, 0, RowCount, result); } /// /// Copies the requested column elements into a new Vector. /// /// The column to copy elements from. /// The row to start copying from. /// The number of elements to copy. /// A Vector containing the requested elements. /// If: /// is negative, /// or greater than or equal to the number of columns. /// is negative, /// or greater than or equal to the number of rows. /// (rowIndex + length) >= Rows. /// /// If is not positive. public virtual Vector Column(int columnIndex, int rowIndex, int length) { var result = CreateVector(length); Column(columnIndex, rowIndex, length, result); return result; } /// /// Copies the requested column elements into the given vector. /// /// The column to copy elements from. /// The row to start copying from. /// The number of elements to copy. /// The Vector to copy the column into. /// If the result Vector is . /// If is negative, /// or greater than or equal to the number of columns. /// If is negative, /// or greater than or equal to the number of rows. /// If + /// is greater than or equal to the number of rows. /// If is not positive. /// If result.Count < length. public virtual void Column(int columnIndex, int rowIndex, int length, Vector result) { if (result == null) { throw new ArgumentNullException("result"); } if (columnIndex >= ColumnCount || columnIndex < 0) { throw new ArgumentOutOfRangeException("columnIndex"); } if (rowIndex >= RowCount || rowIndex < 0) { throw new ArgumentOutOfRangeException("rowIndex"); } if (rowIndex + length > RowCount) { throw new ArgumentOutOfRangeException("length"); } if (length < 1) { throw new ArgumentException(Resources.ArgumentMustBePositive, "length"); } if (result.Count < length) { throw new ArgumentException(Resources.ArgumentVectorsSameLength, "result"); } for (int i = rowIndex, j = 0; i < rowIndex + length; i++, j++) { result[j] = At(i, columnIndex); } } /// /// Returns a new matrix containing the lower triangle of this matrix. /// /// The lower triangle of this matrix. public virtual Matrix LowerTriangle() { var ret = CreateMatrix(RowCount, ColumnCount); CommonParallel.For( 0, ColumnCount, j => { for (var i = j; i < RowCount; i++) { ret.At(i, j, At(i, j)); } }); return ret; } /// /// Puts the lower triangle of this matrix into the result matrix. /// /// Where to store the lower triangle. /// If is . /// If the result matrix's dimensions are not the same as this matrix. public virtual void LowerTriangle(Matrix result) { if (result == null) { throw new ArgumentNullException("result"); } if (result.RowCount != RowCount || result.ColumnCount != ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixDimensions, "result"); } CommonParallel.For( 0, ColumnCount, j => { for (var i = 0; i < RowCount; i++) { result.At(i, j, i >= j ? At(i, j) : default(T)); } }); } /// /// Returns a new matrix containing the upper triangle of this matrix. /// /// The upper triangle of this matrix. public virtual Matrix UpperTriangle() { var ret = CreateMatrix(RowCount, ColumnCount); CommonParallel.For( 0, ColumnCount, j => { for (var i = 0; i < RowCount; i++) { if (i <= j) { ret.At(i, j, At(i, j)); } } }); return ret; } /// /// Puts the upper triangle of this matrix into the result matrix. /// /// Where to store the lower triangle. /// If is . /// If the result matrix's dimensions are not the same as this matrix. public virtual void UpperTriangle(Matrix result) { if (result == null) { throw new ArgumentNullException("result"); } if (result.RowCount != RowCount || result.ColumnCount != ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixDimensions, "result"); } CommonParallel.For( 0, ColumnCount, j => { for (var i = 0; i < RowCount; i++) { result.At(i, j, i <= j ? At(i, j) : default(T)); } }); } /// /// Creates a matrix that contains the values from the requested sub-matrix. /// /// The row to start copying from. /// The number of rows to copy. Must be positive. /// The column to start copying from. /// The number of columns to copy. Must be positive. /// The requested sub-matrix. /// If: is /// negative, or greater than or equal to the number of rows. /// is negative, or greater than or equal to the number /// of columns. /// (columnIndex + columnLength) >= Columns /// (rowIndex + rowLength) >= Rows /// If or /// is not positive. public virtual Matrix SubMatrix(int rowIndex, int rowLength, int columnIndex, int columnLength) { if (rowIndex >= RowCount || rowIndex < 0) { throw new ArgumentOutOfRangeException("rowIndex"); } if (columnIndex >= ColumnCount || columnIndex < 0) { throw new ArgumentOutOfRangeException("columnIndex"); } if (rowLength < 1) { throw new ArgumentException(Resources.ArgumentMustBePositive, "rowLength"); } if (columnLength < 1) { throw new ArgumentException(Resources.ArgumentMustBePositive, "columnLength"); } var colMax = columnIndex + columnLength; var rowMax = rowIndex + rowLength; if (rowMax > RowCount) { throw new ArgumentOutOfRangeException("rowLength"); } if (colMax > ColumnCount) { throw new ArgumentOutOfRangeException("columnLength"); } var result = CreateMatrix(rowLength, columnLength); CommonParallel.For( columnIndex, colMax, j => { for (int i = rowIndex, ii = 0; i < rowMax; i++, ii++) { result.At(ii, j - columnIndex, At(i, j)); } }); return result; } /// /// Returns an that enumerates over the matrix columns. /// /// An that enumerates over the matrix columns /// public virtual IEnumerable>> ColumnEnumerator() { for (var i = 0; i < ColumnCount; i++) { yield return new KeyValuePair>(i, Column(i)); } } /// /// Returns an that enumerates the requested matrix columns. /// /// The column to start enumerating over. /// The number of columns to enumerating over. /// An that enumerates over requested matrix columns. /// /// If: /// is negative, /// or greater than or equal to the number of columns. /// (index + length) >= Columns. /// /// If is not positive. public virtual IEnumerable>> ColumnEnumerator(int index, int length) { if (index >= ColumnCount || index < 0) { throw new ArgumentOutOfRangeException("index"); } if (index + length > ColumnCount) { throw new ArgumentOutOfRangeException("length"); } if (length < 1) { throw new ArgumentException(Resources.ArgumentMustBePositive, "length"); } var maxIndex = index + length; for (var i = index; i < maxIndex; i++) { yield return new KeyValuePair>(i, Column(i)); } } /// /// Returns an that enumerates the requested matrix rows. /// /// The row to start enumerating over. /// The number of rows to enumerating over. /// An that enumerates over requested matrix rows. /// /// If: /// is negative, /// or greater than or equal to the number of rows. /// (index + length) >= Rows. /// If is not positive. public virtual IEnumerable>> RowEnumerator(int index, int length) { if (index >= RowCount || index < 0) { throw new ArgumentOutOfRangeException("index"); } if (index + length > RowCount) { throw new ArgumentOutOfRangeException("length"); } if (length < 1) { throw new ArgumentException(Resources.ArgumentMustBePositive, "length"); } var maxi = index + length; for (var i = index; i < maxi; i++) { yield return new KeyValuePair>(i, Row(i)); } } /// /// Returns an that enumerates over the matrix rows. /// /// An that enumerates over the matrix rows /// public virtual IEnumerable>> RowEnumerator() { for (var i = 0; i < RowCount; i++) { yield return new KeyValuePair>(i, Row(i)); } } /// /// Returns the elements of the diagonal in a Vector. /// /// The elements of the diagonal. /// For non-square matrices, the method returns Min(Rows, Columns) elements where /// i == j (i is the row index, and j is the column index). public virtual Vector Diagonal() { var min = Math.Min(RowCount, ColumnCount); var diagonal = CreateVector(min); CommonParallel.For( 0, min, i => { diagonal[i] = At(i, i); }); return diagonal; } /// /// Returns a new matrix containing the lower triangle of this matrix. The new matrix /// does not contain the diagonal elements of this matrix. /// /// The lower triangle of this matrix. public virtual Matrix StrictlyLowerTriangle() { var result = CreateMatrix(RowCount, ColumnCount); CommonParallel.For( 0, RowCount, i => { for (var j = 0; j < ColumnCount; j++) { if (i > j) { result.At(i, j, At(i, j)); } } }); return result; } /// /// Puts the strictly lower triangle of this matrix into the result matrix. /// /// Where to store the lower triangle. /// If is . /// If the result matrix's dimensions are not the same as this matrix. public virtual void StrictlyLowerTriangle(Matrix result) { if (result == null) { throw new ArgumentNullException("result"); } if (result.RowCount != RowCount || result.ColumnCount != ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixDimensions, "result"); } CommonParallel.For( 0, RowCount, i => { for (var j = 0; j < ColumnCount; j++) { result.At(i, j, i > j ? At(i, j) : default(T)); } }); } /// /// Returns a new matrix containing the upper triangle of this matrix. The new matrix /// does not contain the diagonal elements of this matrix. /// /// The upper triangle of this matrix. public virtual Matrix StrictlyUpperTriangle() { var result = CreateMatrix(RowCount, ColumnCount); CommonParallel.For( 0, RowCount, i => { for (var j = 0; j < ColumnCount; j++) { if (i < j) { result.At(i, j, At(i, j)); } } }); return result; } /// /// Puts the strictly upper triangle of this matrix into the result matrix. /// /// Where to store the lower triangle. /// If is . /// If the result matrix's dimensions are not the same as this matrix. public virtual void StrictlyUpperTriangle(Matrix result) { if (result == null) { throw new ArgumentNullException("result"); } if (result.RowCount != RowCount || result.ColumnCount != ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixDimensions, "result"); } CommonParallel.For( 0, RowCount, i => { for (var j = 0; j < ColumnCount; j++) { result.At(i, j, i < j ? At(i, j) : default(T)); } }); } /// /// Creates a new matrix and inserts the given column at the given index. /// /// The index of where to insert the column. /// The column to insert. /// A new matrix with the inserted column. /// If is . /// If is < zero or > the number of columns. /// If the size of != the number of rows. public virtual Matrix InsertColumn(int columnIndex, Vector column) { if (column == null) { throw new ArgumentNullException("column"); } if (columnIndex < 0 || columnIndex > ColumnCount) { throw new ArgumentOutOfRangeException("columnIndex"); } if (column.Count != RowCount) { throw new ArgumentException(Resources.ArgumentMatrixSameRowDimension, "column"); } var result = CreateMatrix(RowCount, ColumnCount + 1); for (var i = 0; i < columnIndex; i++) { result.SetColumn(i, Column(i)); } result.SetColumn(columnIndex, column); for (var i = columnIndex + 1; i < ColumnCount + 1; i++) { result.SetColumn(i, Column(i - 1)); } return result; } /// /// Copies the values of the given array to the specified column. /// /// The column to copy the values to. /// The array to copy the values from. /// If is . /// If is less than zero, /// or greater than or equal to the number of columns. /// If the size of does not /// equal the number of rows of this Matrix. /// If the size of does not /// equal the number of rows of this Matrix. public virtual void SetColumn(int columnIndex, T[] column) { if (columnIndex < 0 || columnIndex >= ColumnCount) { throw new ArgumentOutOfRangeException("columnIndex"); } if (column == null) { throw new ArgumentNullException("column"); } if (column.Length != RowCount) { throw new ArgumentException(Resources.ArgumentMatrixSameRowDimension, "column"); } CommonParallel.For( 0, RowCount, i => At(i, columnIndex, column[i])); } /// /// Copies the values of the given Vector to the specified column. /// /// The column to copy the values to. /// The vector to copy the values from. /// If is . /// If is less than zero, /// or greater than or equal to the number of columns. /// If the size of does not /// equal the number of rows of this Matrix. public virtual void SetColumn(int columnIndex, Vector column) { if (columnIndex < 0 || columnIndex >= ColumnCount) { throw new ArgumentOutOfRangeException("columnIndex"); } if (column == null) { throw new ArgumentNullException("column"); } if (column.Count != RowCount) { throw new ArgumentException(Resources.ArgumentMatrixSameRowDimension, "column"); } CommonParallel.For( 0, RowCount, i => At(i, columnIndex, column[i])); } /// /// Creates a new matrix and inserts the given row at the given index. /// /// The index of where to insert the row. /// The row to insert. /// A new matrix with the inserted column. /// If is . /// If is < zero or > the number of rows. /// If the size of != the number of columns. public virtual Matrix InsertRow(int rowIndex, Vector row) { if (row == null) { throw new ArgumentNullException("row"); } if (rowIndex < 0 || rowIndex > RowCount) { throw new ArgumentOutOfRangeException("rowIndex"); } if (row.Count != ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSameRowDimension, "row"); } var result = CreateMatrix(RowCount + 1, ColumnCount); for (var i = 0; i < rowIndex; i++) { result.SetRow(i, Row(i)); } result.SetRow(rowIndex, row); for (var i = rowIndex + 1; i < RowCount; i++) { result.SetRow(i, Row(i - 1)); } return result; } /// /// Copies the values of the given Vector to the specified row. /// /// The row to copy the values to. /// The vector to copy the values from. /// If is . /// If is less than zero, /// or greater than or equal to the number of rows. /// If the size of does not /// equal the number of columns of this Matrix. public virtual void SetRow(int rowIndex, Vector row) { if (rowIndex < 0 || rowIndex >= RowCount) { throw new ArgumentOutOfRangeException("rowIndex"); } if (row == null) { throw new ArgumentNullException("row"); } if (row.Count != ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSameRowDimension, "row"); } CommonParallel.For( 0, ColumnCount, i => At(rowIndex, i, row[i])); } /// /// Copies the values of the given array to the specified row. /// /// The row to copy the values to. /// The array to copy the values from. /// If is . /// If is less than zero, /// or greater than or equal to the number of rows. /// If the size of does not /// equal the number of columns of this Matrix. public virtual void SetRow(int rowIndex, T[] row) { if (rowIndex < 0 || rowIndex >= RowCount) { throw new ArgumentOutOfRangeException("rowIndex"); } if (row == null) { throw new ArgumentNullException("row"); } if (row.Length != ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSameRowDimension, "row"); } CommonParallel.For( 0, ColumnCount, i => At(rowIndex, i, row[i])); } /// /// Copies the values of a given matrix into a region in this matrix. /// /// The row to start copying to. /// The number of rows to copy. Must be positive. /// The column to start copying to. /// The number of columns to copy. Must be positive. /// The sub-matrix to copy from. /// If: is /// negative, or greater than or equal to the number of rows. /// is negative, or greater than or equal to the number /// of columns. /// (columnIndex + columnLength) >= Columns /// (rowIndex + rowLength) >= Rows /// If is /// the size of is not at least x . /// If or /// is not positive. public virtual void SetSubMatrix(int rowIndex, int rowLength, int columnIndex, int columnLength, Matrix subMatrix) { if (rowIndex >= RowCount || rowIndex < 0) { throw new ArgumentOutOfRangeException("rowIndex"); } if (columnIndex >= ColumnCount || columnIndex < 0) { throw new ArgumentOutOfRangeException("columnIndex"); } if (rowLength < 1) { throw new ArgumentException(Resources.ArgumentMustBePositive, "rowLength"); } if (columnLength < 1) { throw new ArgumentException(Resources.ArgumentMustBePositive, "columnLength"); } if (subMatrix == null) { throw new ArgumentNullException("subMatrix"); } if (columnLength > subMatrix.ColumnCount) { throw new ArgumentOutOfRangeException("columnLength", @"columnLength can be at most the number of columns in subMatrix."); } if (rowLength > subMatrix.RowCount) { throw new ArgumentOutOfRangeException("rowLength", @"rowLength can be at most the number of rows in subMatrix."); } var colMax = columnIndex + columnLength; var rowMax = rowIndex + rowLength; if (rowMax > RowCount) { throw new ArgumentOutOfRangeException("rowLength"); } if (colMax > ColumnCount) { throw new ArgumentOutOfRangeException("columnLength"); } CommonParallel.For( columnIndex, colMax, j => { for (int i = rowIndex, ii = 0; i < rowMax; i++, ii++) { At(i, j, subMatrix[ii, j - columnIndex]); } }); } /// /// Copies the values of the given Vector to the diagonal. /// /// The vector to copy the values from. The length of the vector should be /// Min(Rows, Columns). /// If is . /// If the length of does not /// equal Min(Rows, Columns). /// For non-square matrices, the elements of are copied to /// this[i,i]. public virtual void SetDiagonal(Vector source) { if (source == null) { throw new ArgumentNullException("source"); } var min = Math.Min(RowCount, ColumnCount); if (source.Count != min) { throw new ArgumentException(Resources.ArgumentVectorsSameLength, "source"); } CommonParallel.For( 0, min, i => At(i, i, source[i])); } /// /// Copies the values of the given array to the diagonal. /// /// The array to copy the values from. The length of the vector should be /// Min(Rows, Columns). /// If is . /// If the length of does not /// equal Min(Rows, Columns). /// For non-square matrices, the elements of are copied to /// this[i,i]. public virtual void SetDiagonal(T[] source) { if (source == null) { throw new ArgumentNullException("source"); } var min = Math.Min(RowCount, ColumnCount); if (source.Length != min) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "source"); } CommonParallel.For( 0, min, i => At(i, i, source[i])); } /// /// Returns this matrix as a multidimensional array. /// /// A multidimensional containing the values of this matrix. public virtual T[,] ToArray() { var ret = new T[RowCount, ColumnCount]; CommonParallel.For( 0, ColumnCount, j => { for (var i = 0; i < RowCount; i++) { ret[i, j] = At(i, j); } }); return ret; } /// /// Returns the matrix's elements as an array with the data laid out column-wise. /// ///
        /// 1, 2, 3
        /// 4, 5, 6  will be returned as  1, 4, 7, 2, 5, 8, 3, 6, 9
        /// 7, 8, 9
        /// 
/// An array containing the matrix's elements. public virtual T[] ToColumnWiseArray() { var ret = new T[RowCount * ColumnCount]; foreach (var column in ColumnEnumerator()) { var columnIndex = column.Key * RowCount; foreach (var element in column.Value.GetIndexedEnumerator()) { ret[columnIndex + element.Key] = element.Value; } } return ret; } /// /// Returns the matrix's elements as an array with the data laid row-wise. /// ///
        /// 1, 2, 3
        /// 4, 5, 6  will be returned as  1, 2, 3, 4, 5, 6, 7, 8, 9
        /// 7, 8, 9
        /// 
/// An array containing the matrix's elements. public virtual T[] ToRowWiseArray() { var ret = new T[RowCount * ColumnCount]; foreach (var row in RowEnumerator()) { var rowIndex = row.Key * ColumnCount; foreach (var element in row.Value.GetIndexedEnumerator()) { ret[rowIndex + element.Key] = element.Value; } } return ret; } #region Implemented Interfaces #if !SILVERLIGHT #region ICloneable /// /// Creates a new object that is a copy of the current instance. /// /// /// A new object that is a copy of this instance. /// object ICloneable.Clone() { return Clone(); } #endregion #endif #region IEquatable> /// /// Indicates whether the current object is equal to another object of the same type. /// /// /// An object to compare with this object. /// /// /// true if the current object is equal to the parameter; otherwise, false. /// public virtual bool Equals(Matrix other) { // Reject equality when the argument is null or has a different shape. if (other == null) { return false; } if (ColumnCount != other.ColumnCount || RowCount != other.RowCount) { return false; } // Accept if the argument is the same object as this. if (ReferenceEquals(this, other)) { return true; } // If all else fails, perform element wise comparison. for (var row = 0; row < RowCount; row++) { for (var column = 0; column < ColumnCount; column++) { if (!At(row, column).Equals(other.At(row, column))) { return false; } } } return true; } #endregion #region IFormattable /// /// Returns a that represents this instance. /// /// /// The format to use. /// /// /// The format provider to use. /// /// /// A that represents this instance. /// public virtual string ToString(string format, IFormatProvider formatProvider) { var stringBuilder = new StringBuilder(); for (var row = 0; row < RowCount; row++) { for (var column = 0; column < ColumnCount; column++) { stringBuilder.Append(At(row, column).ToString(format, formatProvider)); if (column != ColumnCount - 1) { stringBuilder.Append(formatProvider.GetTextInfo().ListSeparator); } } if (row != RowCount - 1) { stringBuilder.Append(Environment.NewLine); } } return stringBuilder.ToString(); } #endregion #endregion /// /// Ranges the check. /// /// /// The row of the element. /// /// /// The column of the element. /// private void RangeCheck(int row, int column) { if (row < 0 || row >= RowCount) { throw new ArgumentOutOfRangeException("row"); } if (column < 0 || column >= ColumnCount) { throw new ArgumentOutOfRangeException("column"); } } #region System.Object overrides /// /// Determines whether the specified is equal to this instance. /// /// The to compare with this instance. /// /// true if the specified is equal to this instance; otherwise, false. /// public override bool Equals(object obj) { return Equals(obj as Matrix); } /// /// Returns a hash code for this instance. /// /// /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// public override int GetHashCode() { var hashNum = Math.Min(RowCount * ColumnCount, 25); long hash = 0; for (var i = 0; i < hashNum; i++) { var col = i % ColumnCount; var row = (i - col) / RowCount; #if SILVERLIGHT hash ^= Precision.DoubleToInt64Bits(this[row, col].GetHashCode()); #else hash ^= BitConverter.DoubleToInt64Bits(this[row, col].GetHashCode()); #endif } return BitConverter.ToInt32(BitConverter.GetBytes(hash), 4); } #endregion /// /// Sets all values to zero. /// public virtual void Clear() { for (var i = 0; i < RowCount; i++) { for (var j = 0; j < ColumnCount; j++) { At(i, j, default(T)); } } } /// /// Returns the transpose of this matrix. /// /// The transpose of this matrix. public virtual Matrix Transpose() { var ret = CreateMatrix(ColumnCount, RowCount); for (var j = 0; j < ColumnCount; j++) { for (var i = 0; i < RowCount; i++) { ret.At(j, i, At(i, j)); } } return ret; } /// /// Returns the conjugate transpose of this matrix. /// /// The conjugate transpose of this matrix. public abstract Matrix ConjugateTranspose(); /// /// Permute the rows of a matrix according to a permutation. /// /// The row permutation to apply to this matrix. public virtual void PermuteRows(Permutation p) { if (p.Dimension != RowCount) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "p"); } // Get a sequence of inversions from the permutation. var inv = p.ToInversions(); for (var i = 0; i < inv.Length; i++) { if (inv[i] != i) { var q = inv[i]; for (var j = 0; j < ColumnCount; j++) { var temp = At(q, j); At(q, j, At(i, j)); At(i, j, temp); } } } } /// /// Permute the columns of a matrix according to a permutation. /// /// The column permutation to apply to this matrix. public virtual void PermuteColumns(Permutation p) { if (p.Dimension != ColumnCount) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "p"); } // Get a sequence of inversions from the permutation. var inv = p.ToInversions(); for (var i = 0; i < inv.Length; i++) { if (inv[i] != i) { var q = inv[i]; for (var j = 0; j < RowCount; j++) { var temp = At(j, q); At(j, q, At(j, i)); At(j, i, temp); } } } } /// /// Concatenates this matrix with the given matrix. /// /// The matrix to concatenate. /// The combined matrix. public virtual Matrix Append(Matrix right) { if (right == null) { throw new ArgumentNullException("right"); } if (right.RowCount != RowCount) { throw new ArgumentException(Resources.ArgumentMatrixSameRowDimension); } var result = CreateMatrix(RowCount, ColumnCount + right.ColumnCount); Append(right, result); return result; } /// /// Concatenates this matrix with the given matrix and places the result into the result matrix. /// /// The matrix to concatenate. /// The combined matrix. public virtual void Append(Matrix right, Matrix result) { if (right == null) { throw new ArgumentNullException("right"); } if (right.RowCount != RowCount) { throw new ArgumentException(Resources.ArgumentMatrixSameRowDimension); } if (result == null) { throw new ArgumentNullException("result"); } if (result.ColumnCount != (ColumnCount + right.ColumnCount) || result.RowCount != RowCount) { throw new ArgumentException(Resources.ArgumentMatrixSameColumnDimension); } CommonParallel.Invoke( () => { for (var i = 0; i < RowCount; i++) { for (var j = 0; j < ColumnCount; j++) { result.At(i, j, At(i, j)); } } }, () => { for (var i = 0; i < RowCount; i++) { for (var j = 0; j < right.ColumnCount; j++) { result.At(i, j + ColumnCount, right.At(i, j)); } } }); } /// /// Stacks this matrix on top of the given matrix and places the result into the result matrix. /// /// The matrix to stack this matrix upon. /// The combined matrix. /// If lower is . /// If upper.Columns != lower.Columns. public virtual Matrix Stack(Matrix lower) { if (lower == null) { throw new ArgumentNullException("lower"); } if (lower.ColumnCount != ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSameColumnDimension, "lower"); } var result = CreateMatrix(RowCount + lower.RowCount, ColumnCount); Stack(lower, result); return result; } /// /// Stacks this matrix on top of the given matrix and places the result into the result matrix. /// /// The matrix to stack this matrix upon. /// The combined matrix. /// If lower is . /// If upper.Columns != lower.Columns. public virtual void Stack(Matrix lower, Matrix result) { if (lower == null) { throw new ArgumentNullException("lower"); } if (lower.ColumnCount != ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSameColumnDimension, "lower"); } if (result == null) { throw new ArgumentNullException("result"); } if (result.RowCount != (RowCount + lower.RowCount) || result.ColumnCount != ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixDimensions, "result"); } CommonParallel.Invoke( () => { for (var i = 0; i < RowCount; i++) { for (var j = 0; j < ColumnCount; j++) { result.At(i, j, At(i, j)); } } }, () => { for (var i = 0; i < lower.RowCount; i++) { for (var j = 0; j < ColumnCount; j++) { result.At(i + RowCount, j, lower.At(i, j)); } } }); } /// /// Diagonally stacks his matrix on top of the given matrix. The new matrix is a M-by-N matrix, /// where M = this.Rows + lower.Rows and N = this.Columns + lower.Columns. /// The values of off the off diagonal matrices/blocks are set to zero. /// /// The lower, right matrix. /// If lower is . /// the combined matrix public virtual Matrix DiagonalStack(Matrix lower) { if (lower == null) { throw new ArgumentNullException("lower"); } var result = CreateMatrix(RowCount + lower.RowCount, ColumnCount + lower.ColumnCount); DiagonalStack(lower, result); return result; } /// /// Diagonally stacks his matrix on top of the given matrix and places the combined matrix into the result matrix. /// /// The lower, right matrix. /// The combined matrix /// If lower is . /// If the result matrix is . /// If the result matrix's dimensions are not (this.Rows + lower.rows) x (this.Columns + lower.Columns). public virtual void DiagonalStack(Matrix lower, Matrix result) { if (lower == null) { throw new ArgumentNullException("lower"); } if (result == null) { throw new ArgumentNullException("result"); } if (result.RowCount != RowCount + lower.RowCount || result.ColumnCount != ColumnCount + lower.ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixDimensions, "result"); } CommonParallel.Invoke( () => { for (var i = 0; i < RowCount; i++) { for (var j = 0; j < ColumnCount; j++) { result.At(i, j, At(i, j)); } } }, () => { for (var i = 0; i < lower.RowCount; i++) { for (var j = 0; j < lower.ColumnCount; j++) { result.At(i + RowCount, j + ColumnCount, lower.At(i, j)); } } }); } /// Calculates the L1 norm. /// The L1 norm of the matrix. public abstract T L1Norm(); /// Calculates the L2 norm. /// The L2 norm of the matrix. /// For sparse matrices, the L2 norm is computed using a dense implementation of singular value decomposition. /// In a later release, it will be replaced with a sparse implementation. public virtual T L2Norm() { return Svd.Create(this, false).Norm2; } /// Calculates the Frobenius norm of this matrix. /// The Frobenius norm of this matrix. public abstract T FrobeniusNorm(); /// Calculates the infinity norm of this matrix. /// The infinity norm of this matrix. public abstract T InfinityNorm(); } }