3

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?

MultiplyByZer0
  • 6,302
  • 3
  • 32
  • 48

1 Answers1

3

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);

apete
  • 1,250
  • 1
  • 10
  • 16
  • Thank you very much for taking the trouble to answer my question. And I would like to personally express my gratitude to you for writing ojalgo! Your answer was very helpful! I had actually read the wiki page you mentioned, but I did not understand it very well since I am relatively new to all this (plus copy-paste from the site failed me miserably due to importing problems). – GerasimosPanagiotakopoulos Aug 25 '15 at 13:27