gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:10 25 4
gpt4 key购买 nike

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

最佳答案

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

在你的例子中:B(2X3) * C(3X2) = Output(2X2)

然而,您的代码使用第一个矩阵的维度定义输出矩阵(如下所示: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;
}

关于java - 如何在这个问题中正确地乘以 2 个矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52536847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com