如何在这个问题上正确地乘以2个矩阵?

时间:2018-09-27 12:17:42

标签: java arrays matrix

这是我的多重方法:

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

在driver方法中,每当有涉及乘矩阵的问题时,要么是错误的,要么是系统出现错误。

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

这是我的 Matrix 类:

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语言的初学者,请原谅我的无知。请帮忙!

2 个答案:

答案 0 :(得分:3)

请注意,矩阵乘法的输出如下:A(nXm) * B (mXk) = C (nXk)

您的情况:B(2X3) * C(3X2) = Output(2X2)

但是您的代码使用第一个维度定义输出矩阵(如此处所示:int multiplication[][] = new int[rows][columns];

为了解决该问题(在内部循环外部设置multiplication[r][c],添加2个小的优化):

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

答案 1 :(得分:1)

首先,新矩阵是this.rows,otherMatrix.columns 当相乘时,您要检查otherMatrix.columns两次,我认为第二个应该是this.columns

 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][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 < columns; i++) {
                sum = sum + matrix[r][i]*otherMatrix.matrix[i][c];
                multiplication[r][c] = sum;
            }
        }
    }
    return new Matrix(multiplication);
}