What's the most efficient way to create a diagonal matrix with ojalgo?

171 Views Asked by At

Is there something like Primitive64Matrix.FACTORY.makeDiagonal(double...)? I couldn't find anything like that in https://www.ojalgo.org/code-examples/

I was hoping not to do Primitive64Matrix.FACTORY.rows(new double[][]{{1, 0, 0}, {0, 2, 0}, {0, 0, 5}}) since that's not exploiting the sparse structure of the diagonal matrix and therefore seems computationally inefficient for big matrices.

1

There are 1 best solutions below

0
On BEST ANSWER

No, not directly like that. You can either create a sparse matrix and then just set the diagonal:

    SparseReceiver sparseReceiver = Primitive64Matrix.FACTORY.makeSparse(3, 3);

    sparseReceiver.fillDiagonal(3.14);

    Primitive64Matrix matrix = sparseReceiver.get();

Using MatrixStore:s there is a DiagonalStore implementation. It is perhaps the closest thing to what you're looking for, but it's not very "direct" to instantiate. You have to do something like this:

    DiagonalStore<Double, Primitive64Array> diagonalStore = DiagonalStore.builder(Primitive64Store.FACTORY, Primitive64Array.wrap(3.14, 3.14, 3.14)).get();

or

    DiagonalStore<Double, Primitive64Array> diagonalStore = Primitive64Store.FACTORY.makeDiagonal(Primitive64Array.wrap(3.14, 3.14, 3.14)).get();

... or you just create your own MatrixStore implementation. That's very easy to do, and there is a code example for that.