为了账号安全,请及时绑定邮箱和手机立即绑定

在java中实现向量乘法

在java中实现向量乘法

莫回无 2021-09-12 16:21:22
目前我正在尝试实现一种能够在java中使用向量和矩阵乘法的方法,现在我有代码:package ai2;public class MyMatrix {    int[][] alpha;    int a;    int b;    int rowsB;    int colsB;    public MyMatrix(int a, int b) {        this.a = a;        this.b = b;        alpha = new int[a][b];        for (int k = 0; k < a; k++) {            for (int l = 0; l < b; l++) {                alpha[k][l] = 0;            }        }    }    public void insertValue(int o, int q, int z) {        this.alpha[o][q] = z;    }    public void print() {        for (int k = 0; k < a; k++) {            for (int l = 0; l < b; l++) {                System.out.print(this.alpha[k][l] + " ");            }            System.out.println();        }    }    public void multiplyMatrix(MyMatrix B) {        MyMatrix created = new MyMatrix(this.a, B.b);        for (int m = 0; m < a; m++) {            for (int k = 0; k < b; k++) {                for (int l = 0; k < this.a; l++) {                    myMatrixC[i][j] += myMatrixA[i][k] * myMatrixB[k][j];                }            }        }    }    public static void main(String[] args) {        MyMatrix a = new MyMatrix(2, 2);        a.insertValue(0, 0, 1);        a.insertValue(1, 1, 1);        a.print();        MyMatrix b = new MyMatrix(2, 2);        b.insertValue(0, 0, 1);        b.insertValue(1, 0, 1);        // System.out.println(a);    }}问题是我的 multiplyMatrix 方法,它需要一个 MyMatrix 对象,但我无法使用例如:MyMatrixA[k][l]我需要某种想法来达到这些值,或者可能是一个更智能的实现,我不能使用 java 之外的包,感谢您的帮助!
查看完整描述

2 回答

?
不负相思意

TA贡献1777条经验 获得超10个赞

替换这一行

myMatrixC[i][j] += myMatrixA[i][k] * myMatrixB[k][j];

created.alpha[i][j] += this.alpha[i][k] * B.alpha[k][j];

或者更好的是,更换

MyMatrix created = new MyMatrix(this.a, B.b);

MyMatrix A = this;MyMatrix C = new MyMatrix(this.a, B.b);

那么你可以做

C.alpha[i][j] += A.alpha[i][k] * B.alpha[k][j];

哪个读得更清楚一点。

最后,不需要alpha在构造函数中用 0进行初始化,这会自动发生。


查看完整回答
反对 回复 2021-09-12
?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

Java 中的方括号仅用于访问数组元素。

您在那里的语法将无法编译,并且您无法以这种方式访问您的矩阵元素。

你为什么不在你getAlphaMyMatrix类中实现一个getter来返回值alpha(或者更好的是,它的一个副本,以确保不变性)?

然后,您可以使用theMatrixInstance.getAlpha()[k][l].

您还可以稍微简化一下并实现一个get采用两个索引的方法。

这将允许您检查给定的索引是否在二维数组的范围内并抛出自定义异常(或返回一些默认值),而不是ArrayIndexOutOfBoundsException您会得到的异常。


查看完整回答
反对 回复 2021-09-12
  • 2 回答
  • 0 关注
  • 311 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信