How to properly multiply 2 matrices in this problem?

Lost Soul :

This is my mult method:

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);
}

In the driver method, whenever there's a question that involves multiplying matrices it's either wrong or I get an error from the system.

i.e.

3BC-4BD //which is

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

This is the error.

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

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

These are the matrices I'm using.

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}});

This is my Matrix class:

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

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

I'm a beginner in the JAVA language so please excuse my ignorance. Please help!

dWinder :

Notice that output of the matrix multiplication is as follow: A(nXm) * B (mXk) = C (nXk)

In your case: B(2X3) * C(3X2) = Output(2X2)

However your code define the output matrix with the dimension of the first one (as can be see here: int multiplication[][] = new int[rows][columns];)

In order to fix that try (add 2 small optimization as set the multiplication[r][c] outside the inner loop):

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;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=94437&siteId=1