Is there a MathNET.Numerics equivalent of Matlab’s sortrows(A, column)
, where A is a Matrix<double>
?
To recall Matlab's documentation:
B = sortrows(A,column) sorts A based on the columns specified in the vector column. For example, sortrows(A,4) sorts the rows of A in ascending order based on the elements in the fourth column. sortrows(A,[4 6]) first sorts the rows of A based on the elements in the fourth column, then based on the elements in the sixth column to break ties.
Similar to my answer to your other question, there's nothing inbuilt but you could use Linq
's OrderBy()
method on an Enumerable
of the matrix's rows. Given a Matrix<double> x
,
x.EnumerateRows()
returns an Enumerable<Vector<double>>
of the matrix's rows. You can then sort this enumerable by the first element of each row (if that's what you want).
In C#,
var y = Matrix<double>.Build.DenseOfRows(x.EnumerateRows().OrderBy(row => row[0]));
Writing this as an extension method:
public static Matrix<double> SortRows(this Matrix<double> x, int sortByColumn = 0, bool desc = false) {
if (desc)
return Matrix<double>.Build.DenseOfRows(x.EnumerateRows().OrderByDescending(row => row[sortByColumn]));
else
return Matrix<double>.Build.DenseOfRows(x.EnumerateRows().OrderBy(row => row[sortByColumn]));
}
which you can then call like so:
var y = x.SortRows(0); // Sort by first column