编写java程序实现矩阵加减乘的运算
时间: 2023-05-21 16:00:47 浏览: 63
好的,以下是一个简单的 Java 程序实现矩阵加减乘的运算:
```java
public class Matrix {
private int[][] data;
private int rows;
private int cols;
public Matrix(int[][] data) {
this.data = data;
this.rows = data.length;
this.cols = data[0].length;
}
public Matrix add(Matrix other) {
if (this.rows != other.rows || this.cols != other.cols) {
throw new IllegalArgumentException("Matrices must have the same dimensions");
}
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = this.data[i][j] + other.data[i][j];
}
}
return new Matrix(result);
}
public Matrix subtract(Matrix other) {
if (this.rows != other.rows || this.cols != other.cols) {
throw new IllegalArgumentException("Matrices must have the same dimensions");
}
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = this.data[i][j] - other.data[i][j];
}
}
return new Matrix(result);
}
public Matrix multiply(Matrix other) {
if (this.cols != other.rows) {
throw new IllegalArgumentException("Number of columns in first matrix must match number of rows in second matrix");
}
int[][] result = new int[this.rows][other.cols];
for (int i = 0; i < this.rows; i++) {
for (int j = 0; j < other.cols; j++) {
int sum = 0;
for (int k = 0; k < this.cols; k++) {
sum += this.data[i][k] * other.data[k][j];
}
result[i][j] = sum;
}
}
return new Matrix(result);
}
}
```
这个类中包含了三个方法,分别是 `add`、`subtract` 和 `multiply`,分别用于实现矩阵的加法、减法和乘法运算。这些方法都接受一个 `Matrix` 类型的参数,表示另一个矩阵,然后返回一个新的 `Matrix` 对象,表示运算的结果。