/// <summary>
/// Sorts the given Matrix by the specified row or column selector and returns the new Matrix
/// along with the original indices.
/// </summary>
/// <param name="source">The Matrix</param>
/// <param name="keySelector">Property selector to sort by.</param>
/// <param name="t">Specifies whether to sort horizontally or vertically.</param>
/// <param name="ascending">Determines whether to sort ascending or descending (Default: True)</param>
/// <param name="indices">Vector of <paramref name="t"/> indices in the original Matrix before the sort operation.</param>
/// <returns>New Matrix and Vector of original indices.</returns>
public static Matrix Sort(Matrix source, Func <Vector, double> keySelector, VectorType t, bool ascending, out Vector indices)
{
int max = (t == VectorType.Row ? source.Rows : source.Cols);
indices = Vector.Zeros(max);
List <Vector> vects = new List <Vector>(max);
IEnumerable <Vector> arrays = (t == VectorType.Row ? source.GetRows() : source.GetCols());
KeyValuePair <Vector, int>[] sort = (ascending ?
arrays.Select((i, v) => new KeyValuePair <Vector, int>(i, v))
.OrderBy(o => keySelector(o.Key))
:
arrays.Select((i, v) => new KeyValuePair <Vector, int>(i, v))
.OrderByDescending(o => keySelector(o.Key))).ToArray();
indices = sort.Select(s => s.Value).ToVector();
return(sort.Select(s => s.Key).ToMatrix(t));
}