2

From my understanding, a 2 dimensional matrix that is used in mathematics can be created in Java using a 2 dimensional array. There are of course things you can do with real math matrixes such as adding and subtracting them. With Java however, you would need to write code to do that and there are libraries available that provide that functionality.

What I would like to know though is whether a Java array is even an optimal way of dealing with matrix data. I can think of cases where a 2d matrix has some of its indexes filled in while many are just left blank due to the nature of the data. For me this raises the question whether this is a waste of memory space, especially if the matrix is very large and has a lot of empty indexes.

Do specialized Java math libraries deal with matrixes differently and don't rely upon a 2d array? Or do they use a regular Java array as well and just live with wasted memory?

Johann
  • 27,536
  • 39
  • 165
  • 279
  • On efficiency, take a look at https://codereview.stackexchange.com/questions/40246/given-nn-matrix-rotate-it-by-90-degree-to-left-and-right-without-extra-memory/40372 . There are sophisticated java math libraries with a sparse matrix and other stuff. – Joop Eggen Oct 30 '18 at 15:58

1 Answers1

5

A few things:

  1. Never create matrices of 2 dimensional arrays. It's always preferable to have 1 dimensional array with class accessors that take 2 parameters. The reason is purely for performance. When you allocate a contiguous chunk of memory, you give the CPU the chance to allocate the whole matrix in one memory page, which will minimize cache misses, and hence boost performance.

  2. Matrices with many zeros are called sparse matrices. It's always a trade-off between using sparse matrices and having many zeros in your array.

    • A contiguous array will allow the compiler to use vector operations, such as SIMD, for addition, subtraction, etc.
    • A non-contiguous array will be faster if the relative number of zeros is really high, and you implement it in a smart way.
  3. I don't believe java provides a library for sparse matrices, but I'm sure there's some out there. I'm a C++ dev, and I came to this question because I dealt with matrices a lot during my academic life. A famous C++ library with easy and high-level interface is Armadillo.

Hope this helps.

The Quantum Physicist
  • 24,987
  • 19
  • 103
  • 189
  • 1
    IMO matrix math in java is a huge pain point and there's no clear winner for library. That said, I usually go with Efficient Java Matrix Library. It's fairly efficient as long as matrix sizes don't become massive. – flakes Oct 30 '18 at 16:03