简体   繁体   English

Java中的数学矩阵

[英]A math matrix in Java

From my understanding, a 2 dimensional matrix that is used in mathematics can be created in Java using a 2 dimensional array. 根据我的理解,可以在Java中使用二维数组来创建用于数学的二维矩阵。 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. 但是,使用Java,您将需要编写代码来做到这一点,并且有可用的库来提供该功能。

What I would like to know though is whether a Java array is even an optimal way of dealing with matrix data. 我想知道的是Java数组是否甚至是处理矩阵数据的最佳方法。 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? 专门的Java数学库对矩阵的处理方式是否有所不同,并且不依赖于二维数组? Or do they use a regular Java array as well and just live with wasted memory? 还是他们也使用常规的Java数组,只是浪费内存?

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. 一维数组最好带有带有2个参数的类访问器。 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. 当分配连续的内存块时,CPU就有机会在一个内存页面中分配整个矩阵,这将最大程度地减少缓存未命中,从而提高性能。

  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. 连续数组将允许编译器使用向量运算(例如SIMD )进行加法,减法等。
    • 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. 我不相信Java为稀疏矩阵提供了一个库,但是我敢肯定那里有一些。 I'm a C++ dev, and I came to this question because I dealt with matrices a lot during my academic life. 我是一个C ++开发,我来到了这个问题,因为我在我的学术生涯中处理矩阵很多 A famous C++ library with easy and high-level interface is Armadillo . Armadillo是著名的具有简单且高级接口的C ++库。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM