この問題でどのように適切に乗算2つの行列?

失われた魂 :

これは私のMULTメソッドです。

public Matrix mult(Matrix otherMatrix) {
if(!colsEqualsOthersRows(otherMatrix)) // checks if Matrix A has the same number of columns as Matrix B has rows 
        return null;
    int multiplication[][] = new int[rows][columns];
    for(int r = 0; r < rows; r++) {
        for(int c = 0; c < otherMatrix.columns; c++) {
            int sum = 0;
            for(int i = 0; i < otherMatrix.columns; i++) {
                sum = sum + matrix[r][i]*otherMatrix.matrix[i][c];
                multiplication[r][c] = sum;
            }
        }
    }
return new Matrix(multiplication);
}

乗算行列を必要とする質問がありますたびドライバ方式では、それはどちらか間違っているか、私はシステムからエラーが発生します。

すなわち

3BC-4BD //which is

B.mult(3).mult(C)).subtract(B.mult(4).mult(D));

これはエラーです。

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2

at lab1.Matrix. mult(Matrix.java:81)
at lab1.Driver. main(Driver.java:128)

これらは、私が使用している行列です。

Matrix A = new Matrix(new int[][] {{1,-2,3},{1,-1,0}});
    Matrix B = new Matrix(new int[][] {{3,4},{5,-1},{1,-1}});
    Matrix C = new Matrix(new int[][] {{4,-1,2},{-1,5,1}});
    Matrix D = new Matrix(new int[][] {{-1,0,1},{0,2,1}});
    Matrix E = new Matrix(new int[][] {{3,4},{-2,3},{0,1}});
    Matrix F = new Matrix(new int[][] {{2},{-3}});
    Matrix G = new Matrix(new int[][] {{2,-1}});

これは私であるマトリックスクラス:

public class Matrix { 
    int [][] matrix; 
    int rows, columns; 

    public Matrix (int[][] m) { 
        this.matrix = m; 
        this.rows = m.length; 
        this.columns = m[0].length; 
    }
} 

私は、Java言語で初心者ですので、私の無知を言い訳してください。助けてください!

dWinder:

:マトリックス乗算の出力は以下の通りであることに注意してください A(nXm) * B (mXk) = C (nXk)

あなたの場合: B(2X3) * C(3X2) = Output(2X2)

しかし、あなたのコードは、最初の1の大きさで出力行列を定義します(ここで見ることができるとおりint multiplication[][] = new int[rows][columns];

(セットとして2小さな最適化を追加することを試みを固定するためにmultiplication[r][c]外側にインナーループ)。

int multiplication[][] = new int[rows][otherMatrix.columns];
for(int r = 0; r < rows; r++) {
    for(int c = 0; c < otherMatrix.columns; c++) {
        int sum = 0;
        for(int i = 0; i < otherMatrix.columns; i++)
            sum += matrix[r][i]*otherMatrix.matrix[i][c];
        multiplication[r][c] = sum;
    }

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=205640&siteId=1