java写一个矩阵
时间: 2023-12-18 17:04:25 浏览: 23
以下是Java中的矩阵类示例:
```java
public class Matrix {
private final int rows;
private final int cols;
private final double[][] data;
public Matrix(int rows, int cols) {
this.rows = rows;
this.cols = cols;
this.data = new double[rows][cols];
}
public Matrix(double[][] data) {
this.rows = data.length;
this.cols = data[0].length;
this.data = data;
}
public int getRows() {
return rows;
}
public int getCols() {
return cols;
}
public double get(int i, int j) {
return data[i][j];
}
public void set(int i, int j, double value) {
data[i][j] = value;
}
public Matrix add(Matrix other) {
if (this.rows != other.rows || this.cols != other.cols) {
throw new IllegalArgumentException("Matrices must have the same dimensions");
}
Matrix result = new Matrix(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result.set(i, j, this.get(i, j) + other.get(i, j));
}
}
return result;
}
public Matrix multiply(Matrix other) {
if (this.cols != other.rows) {
throw new IllegalArgumentException("The number of columns in the first matrix must be equal to the number of rows in the second matrix");
}
Matrix result = new Matrix(this.rows, other.cols);
for (int i = 0; i < result.rows; i++) {
for (int j = 0; j < result.cols; j++) {
double sum = 0.0;
for (int k = 0; k < this.cols; k++) {
sum += this.get(i, k) * other.get(k, j);
}
result.set(i, j, sum);
}
}
return result;
}
public void print() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
}
```
此示例实现了矩阵的基本操作,例如创建矩阵、获取和设置矩阵元素、矩阵加法和乘法。您可以使用此类创建和操作矩阵。例如,以下代码创建两个矩阵并对它们执行加法和乘法操作:
```java
public static void main(String[] args) {
double[][] data1 = {{1.0, 2.0}, {3.0, 4.0}};
double[][] data2 = {{5.0, 6.0}, {7.0, 8.0}};
Matrix matrix1 = new Matrix(data1);
Matrix matrix2 = new Matrix(data2);
Matrix sum = matrix1.add(matrix2);
Matrix product = matrix1.multiply(matrix2);
System.out.println("Matrix 1:");
matrix1.print();
System.out.println("Matrix 2:");
matrix2.print();
System.out.println("Sum:");
sum.print();
System.out.println("Product:");
product.print();
}
```
输出结果如下:
```
Matrix 1:
1.0 2.0
3.0 4.0
Matrix 2:
5.0 6.0
7.0 8.0
Sum:
6.0 8.0
10.0 12.0
Product:
19.0 22.0
43.0 50.0
```