我在Java中使用Jama进行矩阵运算,但是由于它们没有稀疏矩阵,所以我开始使用Parallel Cold Library (PColt)。它是Colt的多线程版本。我试图将两个平方矩阵AxB相乘(这是矩阵矩阵乘法,不是元素级(或标量)乘法),大小(NxN)。我找不到PColt中提供的矩阵矩阵乘法的方法(我不t想要逐元素相乘),因此我将方法编码如下。当我将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;等效于A.zMult(B,C,1,0,false,false)

在此,请谨慎对待参数的顺序,因为结果保存到最后一个参数,即C...。确实花了我很多时间:|

最佳答案

矩阵乘法方法在DoubleAlgebra类中。

DenseDoubleAlgebra algebra = new DenseDoubleAlgebra();
DoubleMatrix2D productMatrix = algebra.mult(aMatrix, anotherMatrix);

09-25 22:23
查看更多