目前我正在尝试实现一种能够在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 之外的包,感谢任何帮助!
Java 中的方括号仅用于访问数组元素。
您的语法将无法编译,并且您无法以这种方式访问矩阵元素。
为什么不在MyMatrix
类中实现一个getAlpha
getter,它返回alpha
的值(或者更好的是,返回其副本,以确保不可变性(?
然后,您可以使用theMatrixInstance.getAlpha()[k][l]
引用它。
您还可以简化一点并实现一个采用两个索引的get
方法。
这将允许您检查给定的索引是否在二维数组的范围内,并抛出自定义异常(或返回一些默认值(,而不是您本来会得到的ArrayIndexOutOfBoundsException
。
替换此行
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];
读起来更清楚一点。
最后,无需在构造函数中使用 0 初始化alpha
,这会自动发生。