2013-04-02 218 views
0

我在使用Jama进行java中的矩阵运算,但由于它们没有稀疏矩阵,我开始使用Parallel Cold Library (PColt)。它是Colt的多线程版本。我尝试乘以两个矩形矩阵AxB(它是矩阵 - 矩阵乘法,非元素(或标量)乘法),大小(NxN)。我找不到在PColt中提供的矩阵 - 矩阵乘法的方法(I don' t想要元素乘法),所以我编码的方法如下。当我乘以N = 1000两个矩阵时,花了将近5分钟才完成。 如果有人知道如何在pcolt中乘以两个矩阵,它将会非常感激。 或者如果您发现代码中存在任何不必要的错误并且使得复杂度较高,请通知我。我的方法如下:Java矩阵运算,并行柯尔特矩阵 - 矩阵乘法

/** 
* 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道基,我得到了解决。 其实忘了上面的代码。 PColt提供矩阵矩阵乘法,但方法名称很混乱。

反正为了muliply两个矩阵使用以下方法:

公共DoubleMatrix2D zMult(DoubleMatrix2D B, DoubleMatrix2D C) 线性代数矩阵的矩阵乘法; C = A×B;相当于A.zMult(B,C,1,0,假的,假的)

这里必须注意参数的顺序,因为结果保存到最后一个参数,即Ç ....这真的花费我很多时间:|

回答

2

矩阵乘法法在DoubleAlgebra类中。

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