乘以Java的两个矩阵 [英] Multiplying two matrices in Java
问题描述
我目前正在开发一个类来重新present矩阵,它重新presents任何一般MXN矩阵。我已经制定了加法和标量乘法,但我奋力开拓两个矩阵的乘法。矩阵的数据在双打的二维数组举行。
I am currently developing a class to represent matrices, it represents any general mxn matrix. I have worked out addition and scalar multiplication but I am struggling to develop the multiplication of two matrices. The data of the matrix is held in a 2D array of doubles.
该方法看起来有点像这样:
The method looks a little bit like this:
public Matrix multiply(Matrix A) {
////code
}
这将返回产品矩阵。这是在右边的乘法运算。所以,如果我叫A.multiply(B),那么它将返回矩阵AB与B上的权利。
It will return the product matrix. This is multiplication on the right. So, if I called A.multiply(B) then it would return the matrix AB, with B on the right.
我还不需要担心检查乘法是否在给定矩阵的定义,我认为我会得到正确的尺寸的矩阵。
I don't yet need to worry about checking whether the multiplication is defined on the given matrices, I can assume that I will be given matrices of the correct dimensions.
有谁知道一个简单的算法,甚至可能在伪code进行乘法处理?
Does anyone know of an easy algorithm, possibly even in pseudocode to carry out the multiplication process?
在此先感谢。
推荐答案
矩阵A(长x米)和B(m×n个)的数学的产品被定义为矩阵C(L×n个)组成的元素:
Mathematically the Product of Matrices A (l x m) and B (m x n) is defined as a Matrix C (l x n) consisting of the elements:
m
c_i_k = ∑ a_i_k * b_k_i
k=1
所以,如果你没有太多的为速度,你可能会高兴与直线前进为O(n ^ 3)实现:
So if you're not too much up for speed you might be happy with the straight forward O(n^3) implementation:
for (int i=0; i<l; ++i)
for (int j=0; j<n; ++j)
for (int k=0; k<m; ++k)
c[i][k] += a[i][k] * b[k][j]
相反,如果你正在为你的速度可能要检查像施特拉森算法ohther替代品(见:施特拉森算法)。
If instead you're up for speed you might want to check for ohther alternatives like Strassen algorithm (see: Strassen algorithm).
不过被警告 - 特别是如果你对现代处理器archtitectures乘小矩阵速度在很大程度上取决于排列的方式来使尽其用的高速缓存行矩阵数据和乘法秩序
Nevertheless be warned - especially if you're multiplying small matrices on modern processor archtitectures speed heavily depends on matrix data and multiplication order arranged in a way to make best use of in cache lines.
我强烈怀疑会有任何机会从withing虚拟机的影响这一因素,所以我不知道这是要考虑的。
I strongly doubt there will be any chance to influence this factor from withing a vm, so I'm not sure if this is to be taken into consideration.
这篇关于乘以Java的两个矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!