1

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.

Conrad
  • 2,197
  • 28
  • 53

1 Answers1

1

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

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • One additional aspect of `unique()` is that it sorts as well. I'll need to add a sorting mechanism in there too, but otherwise this works. – Conrad Oct 21 '20 at 15:28
  • 1
    That's fairly simple to add and I modified my answer. I'm not a big fan of Matlab's sorting of the matrix unless you explicitly specify that you don't want it sorted, so I like having two separate functions for them. If you'd like it in a single function, it's easy enough to do. – Pranav Hosangadi Oct 21 '20 at 15:39