user642308
user642308

Reputation: 33

ojalgo : How to sort each row of a matrix?

I have a question about using the oj algo library,

I would like to know if there is an easy and efficient way to take a row out of a Primitive64Matrix, sort it, and then replace it in the matrix, Or alternatively to sort each row of a Primitive64Matrix (but even then I would still like to know how to fill a row of a matrix efficiently)

Here is what I'm doing now :


        final double[][] tab = {
            {
                1, 3, 4, 2 },
            {
                0, 4, 3, 1 } };
        Primitive64Matrix matrix = Primitive64Matrix.FACTORY.rows(tab);
        for (int iRow = 0; iRow < matrix.countRows(); iRow++) {
            final double[] rowSorted = matrix.row(iRow).toRawCopy1D();

            Arrays.sort(rowSorted);
            final Primitive64Matrix.DenseReceiver receiver = matrix.copy();
            receiver.fillRow(iRow, Primitive64Matrix.FACTORY.rows(rowSorted));
            matrix = receiver.get();
        }

I think it's ugly and surely they must be other more efficient ways to do that (especially the .copy is awful)

Upvotes: 1

Views: 245

Answers (1)

apete
apete

Reputation: 1320

Primitive64Matrix is immutable. Maybe you'll find it more natural to work with the various classes in the org.ojalgo.matrix.store package. Further, Primitive64Matrix has been renamed MatrixR064 in newer versions.

Here something you can do, that is close to what you're currently doing:

    double[][] tab = { { 1, 3, 4, 2 }, { 0, 4, 3, 1 } };
    MatrixR064 matrix = MatrixR064.FACTORY.rows(tab);

    DenseReceiver receiver = matrix.copy();

    ArrayR064 temp = ArrayR064.make(matrix.getColDim());

    for (RowView<Double> view : matrix.rows()) {
        view.supplyTo(temp.data);
        Arrays.sort(temp.data);
        receiver.fillRow(view.row(), temp);
    }

    matrix = receiver.get();

If you use Primitive64Store (not yet renamed) instead of MatrixR064 you can avoid copying the matrix, but still do essentially the same thing as above.

    double[][] tab = { { 1, 3, 4, 2 }, { 0, 4, 3, 1 } };
    Primitive64Store matrix = Primitive64Store.FACTORY.rows(tab);

    ArrayR064 temp = ArrayR064.make(matrix.getColDim());

    for (RowView<Double> view : matrix.rows()) {
        view.supplyTo(temp.data);
        Arrays.sort(temp.data);
        matrix.fillRow(view.row(), temp);
    }

Upvotes: 0

Related Questions