Search code examples
javaarraysmatrixojalgo

Using ojalgo: Create Matrix from Array


I am trying to use ojAlgo to solve some linear algebra problems in Java. I am asking if there is any "clever" way to create a matrix using an existent array.

This is my naive approach:

final double[][] myArray = {
    { 1.1, 1.2, 1.3, 1.4, 1.5 },
    { 2.1, 2.2, 2.3, 2.4, 2.5 },
    { 3.1, 3.2, 3.3, 3.4, 3.5 }
};

final Builder<PrimitiveMatrix> myBuilder = PrimitiveMatrix.getBuilder(myArray.length, myArray[0].length);
for (int i = 0; i < myArray.length; i++) {
    for (int j = 0; j < myArray[0].length; j++) {
        myBuilder.set(i, j, myArray[i][j]);
    }
}

final PrimitiveMatrix myMatrix = myBuilder.build();
System.out.println(myMatrix);

This works, but it is too much trouble to do every single time. I could write a class that does just that and call it every time I want to do it, but I wonder if there is a simpler approach.

Is there a simpler approach?


Solution

  • Do you really want to create an (immutable) BasicMatrix instance? and did you read the ojAlgo Getting Started wiki page regarding choosing between different matrix implementations and how to instantiate them?

    There is a class/method org.ojalgo.array.ArrayUtils#wrapAccess2D(double[][]) that may help you, but that depends on what your next step is...

    ...or why don't you simply call PrimitiveMatrix.FACTORY.rows(myArray);