public Array2DRowRealMatrix multiply(Array2DRowRealMatrix m) { //MatrixUtils.checkMultiplicationCompatible(this, m); int nRows = getRowDimension(); int nCols = m.getColumnDimension(); int nSum = getColumnDimension(); double[][] outData = Java.CreateArray <double[][]>(nRows, nCols);// new double[nRows][nCols]; // Will hold a column of "m". double[] mCol = new double[nSum]; double[][] mData = m.data; // Multiply. for (int col = 0; col < nCols; col++) { // Copy all elements of column "col" of "m" so that // will be in contiguous memory. for (int mRow = 0; mRow < nSum; mRow++) { mCol[mRow] = mData[mRow][col]; } for (int row = 0; row < nRows; row++) { double[] dataRow = data[row]; double sum = 0; for (int i = 0; i < nSum; i++) { sum += dataRow[i] * mCol[i]; } outData[row][col] = sum; } } return(new Array2DRowRealMatrix(outData, false)); }
public LUDecomposition(Array2DRowRealMatrix matrix, double singularityThreshold) { // if (!matrix.isSquare()) { // throw new NonSquareMatrixException(matrix.getRowDimension(), // matrix.getColumnDimension()); //} int m = matrix.getColumnDimension(); lu = matrix.getData(); pivot = new int[m]; cachedL = null; cachedU = null; cachedP = null; // Initialize permutation array and parity for (int row = 0; row < m; row++) { pivot[row] = row; } even = true; singular = false; // Loop over columns for (int col = 0; col < m; col++) { // upper for (int row = 0; row < col; row++) { double[] luRow = lu[row]; double sum = luRow[col]; for (int i = 0; i < row; i++) { sum -= luRow[i] * lu[i][col]; } luRow[col] = sum; } // lower int max = col; // permutation row double largest = double.NegativeInfinity; for (int row = col; row < m; row++) { double[] luRow = lu[row]; double sum = luRow[col]; for (int i = 0; i < col; i++) { sum -= luRow[i] * lu[i][col]; } luRow[col] = sum; // maintain best permutation choice if (Math.Abs(sum) > largest) { largest = Math.Abs(sum); max = row; } } // Singularity check if (Math.Abs(lu[max][col]) < singularityThreshold) { singular = true; return; } // Pivot if necessary if (max != col) { double tmp = 0; double[] luMax = lu[max]; double[] luCol = lu[col]; for (int i = 0; i < m; i++) { tmp = luMax[i]; luMax[i] = luCol[i]; luCol[i] = tmp; } int temp = pivot[max]; pivot[max] = pivot[col]; pivot[col] = temp; even = !even; } // Divide the lower elements by the "winning" diagonal elt. double luDiag = lu[col][col]; for (int row = col + 1; row < m; row++) { lu[row][col] /= luDiag; } } }