java设计矩阵类matrix代码
时间: 2023-10-30 21:08:48 浏览: 85
以下是Java中设计矩阵类Matrix的代码:
```
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.clone();
}
public Matrix multiply(Matrix other) {
if (this.cols != other.rows) {
throw new IllegalArgumentException("Matrices sizes are not compatible for multiplication");
}
double[][] result = new double[this.rows][other.cols];
for (int i = 0; i < this.rows; i++) {
for (int j = 0; j < other.cols; j++) {
for (int k = 0; k < this.cols; k++) {
result[i][j] += this.data[i][k] * other.data[k][j];
}
}
}
return new Matrix(result);
}
public Matrix transpose() {
double[][] result = new double[this.cols][this.rows];
for (int i = 0; i < this.rows; i++) {
for (int j = 0; j < this.cols; j++) {
result[j][i] = this.data[i][j];
}
}
return new Matrix(result);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (double[] row : this.data) {
builder.append(Arrays.toString(row)).append("\n");
}
return builder.toString();
}
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)