Search code examples
c#matlabmathnet-numerics

Equivalent functionality of Matlab unique() in MathNET.Numerics?


Is there a MathNET.Numerics equivalent of Matlab’s unique(A, 'rows') (or unique(A)), where A is a Matrix<double>?

I have searched extensively through the MathNET.Numerics library documentation, and cannot find anything resembling this functionality. Does similar functionality already exist?

To recall Matlab's documentation:

C = unique(A,'rows') treats each row of A as a single entity and returns the unique rows of A. The rows of the array C are in sorted order.


Solution

  • There's nothing inbuilt, but you could use Linq's Distinct() method on an Enumerable of the matrix's rows. Given a Matrix<double> x,

    var y = Matrix<double>.Build.DenseOfRows(x.EnumerateRows().Distinct());
    

    Example

    Writing this as an extension method:

    public static Matrix<double> Unique(this Matrix<double> x) {
        return Matrix<double>.Build.DenseOfRows(x.EnumerateRows().Distinct());
    }
    

    Which you can then call as:

    var y = x.Unique();
    

    This doesn't sort the rows. If you want that, you could combine this with this answer.

    public static Matrix<double> UniqueSorted(this Matrix<double> x, int sortByColumn = 0, bool desc = false) {
        var uq = x.EnumerateRows().Distinct();
        if (desc)
            return Matrix<double>.Build.DenseOfRows(uq.OrderByDescending(row => row[sortByColumn]));
        else
            return Matrix<double>.Build.DenseOfRows(uq.OrderBy(row => row[sortByColumn]));
    }
    

    Here's a big fiddle containing everything