Wednesday, July 3, 2013

New matrix operations: shuffle and rotate

The la4j (Linear Algebra for Java) has recently got two pull-requests (#48, #50) by Jakob Moellers, who implemented two new methods in Matrix interface. Jakob added support for shuffle() (also works for vectors) and rotate() methods. Here is the brief introduction into these methods.
The Matrix.rotate() method is pretty simple. It rotates the matrix by 90 degrees. Here is the example:
Matrix a = new Basic1DMatrix(new double[][] {
  { 1.0, 2.0 },
  { 3.0, 4.0 }
});

/*
Matrix {
 3.0, 1.0
 4.0, 2.0
}
*/
Matrix b = a.rotate();

The shuffle() method can be used with matrices as well as with vector. It shuffles the element of matrix or vector by using Fisher-Yates algorithm. Here is the example.
Matrix a = new Basic1DMatrix(new double[][] {
  { 1.0, 2.0, 3.0 },
  { 4.0, 5.0, 6.0 }
});

/*
Matrix {
 3.0, 5.0, 4.0
 6.0, 1.0, 2.0
}
*/
Matrix b = a.shuffle();

Vector c = new CompressedVector(new double[] { 1.0, 2.0, 3.0 });

// Vector { 2.0, 3.0, 1.0 }
Vector d = c.shuffle();
Thanks Jakob for the great job!

2 comments:

  1. Here's a mistake with this code:

    Matrix a = new Basic1DMatrix(new double[] {
    { 1.0, 2.0 },
    { 3.0, 4.0 }
    });

    should be written like that:

    Matrix a = new Basic1DMatrix(new double[][] {
    { 1.0, 2.0 },
    { 3.0, 4.0 }
    });

    ReplyDelete