我在java中使用Jama进行矩阵运算,但由于它们没有稀疏矩阵,所以我开始使用Parallel Cold Library (PColt) 。它是 Colt 的多线程版本。我尝试将两个方阵相乘,AxB(它是矩阵-矩阵乘法,而不是元素(或标量)乘法),大小(NxN)。我在 PColt 中找不到提供的矩阵-矩阵乘法方法(我不知道)不需要元素乘法),因此我对该方法进行了如下编码。当我将两个矩阵相乘 N=1000 时,几乎需要 5 分钟才能完成。 如果有人知道如何在 pcolt 中将两个矩阵相乘,那将非常感激。 或者,如果您发现代码中有任何不必要的错误并且使复杂性很高,请通知我。我的方法如下:
/**
* Linear algebraic matrix-matrix multiplication; (new)A = A x B. A[i,j] =
* Sum(A[i,k] * B[k,j]), k=0..n-1. Matrix shapes: A(m x n), B(n x p), A(m x
* p).
*
* @param matrix1
* first matrix
* @param matrix2
* second matrix
* @return changes matrix1 with new values matrix-matrix multiplication
*/
public static FloatMatrix2D multiplyMatrix(FloatMatrix2D matrix1,
FloatMatrix2D matrix2) {
// create a matrix same size of input matrix
FloatMatrix2D resultMatrix = matrix1.like();
// matrix-matrix multiplication row of first matrix must be equal to
// column of second matrix
if (matrix1.rows() == matrix2.columns()) {
for (int i = 0; i < matrix1.rows(); i++) {
for (int j = 0; j < matrix2.columns(); j++) {
FloatMatrix1D rowVec = getRow(matrix1, i).copy();
FloatMatrix1D colVec = getCol(matrix2, j).copy();
// first multiplies each row with each column and then sum
// up the result and assign the result to value of matrix
float multOfVects = rowVec.assign(colVec,
FloatFunctions.mult).aggregate(FloatFunctions.plus,
FloatFunctions.identity);
// set sum of vectors to the new matrix
resultMatrix.setQuick(i, j, multOfVects);
}
System.out.println(" i th row "+ i);
}
} else {
System.err
.println("Row size of first matrix must be equal to Column size of second matrix: "
+ matrix1 + " != " + matrix2);
}
return resultMatrix;
}
解决方案...
Okie Dokie,我找到了解决方案。 其实上面的代码忘记了。 PColt 提供了矩阵-矩阵乘法,但方法名称令人困惑。为了将两个矩阵相乘,请使用以下方法:
public DoubleMatrix2D zMult(DoubleMatrix2D B,
DoubleMatrix2D C)
线性代数矩阵-矩阵乘法; C = A x B;
这里要注意参数的顺序,因为结果会保存到最后一个参数C
。 C
也可以设置为 null,这会导致返回一个新矩阵。
最佳答案
矩阵乘法方法位于DoubleAlgebra
类中。
DenseDoubleAlgebra algebra = new DenseDoubleAlgebra();
DoubleMatrix2D productMatrix = algebra.mult(aMatrix, anotherMatrix);
关于Java矩阵运算,并行colt矩阵——矩阵乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15754643/