java 矩阵运算源代码
时间: 2023-06-23 21:47:30 浏览: 50
MatrixOps-开源
以下是 Java 实现的矩阵运算的源代码:
```java
public class Matrix {
private int rows;
private int columns;
private double[][] data;
public Matrix(int rows, int columns) {
this.rows = rows;
this.columns = columns;
this.data = new double[rows][columns];
}
public Matrix(double[][] data) {
this.rows = data.length;
this.columns = data[0].length;
this.data = new double[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
this.data[i][j] = data[i][j];
}
}
}
public int getRows() {
return rows;
}
public int getColumns() {
return columns;
}
public double[][] getData() {
return data;
}
public void set(int row, int column, double value) {
data[row][column] = value;
}
public double get(int row, int column) {
return data[row][column];
}
public Matrix add(Matrix other) {
if (rows != other.rows || columns != other.columns) {
throw new IllegalArgumentException("Matrices must have the same dimensions");
}
Matrix result = new Matrix(rows, columns);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result.set(i, j, data[i][j] + other.get(i, j));
}
}
return result;
}
public Matrix subtract(Matrix other) {
if (rows != other.rows || columns != other.columns) {
throw new IllegalArgumentException("Matrices must have the same dimensions");
}
Matrix result = new Matrix(rows, columns);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result.set(i, j, data[i][j] - other.get(i, j));
}
}
return result;
}
public Matrix multiply(Matrix other) {
if (columns != other.rows) {
throw new IllegalArgumentException("Matrices are not compatible for multiplication");
}
Matrix result = new Matrix(rows, other.columns);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < other.columns; j++) {
double sum = 0;
for (int k = 0; k < columns; k++) {
sum += data[i][k] * other.get(k, j);
}
result.set(i, j, sum);
}
}
return result;
}
public Matrix transpose() {
Matrix result = new Matrix(columns, rows);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result.set(j, i, data[i][j]);
}
}
return result;
}
public void print() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
}
```
这个类包含了矩阵的基本运算,如加法、减法、乘法和转置。可以使用以下代码来测试这个类的功能:
```java
public static void main(String[] args) {
double[][] data1 = {{1, 2, 3}, {4, 5, 6}};
double[][] data2 = {{7, 8}, {9, 10}, {11, 12}};
Matrix matrix1 = new Matrix(data1);
Matrix matrix2 = new Matrix(data2);
Matrix sum = matrix1.add(matrix2);
System.out.println("Sum:");
sum.print();
Matrix difference = matrix1.subtract(matrix2);
System.out.println("Difference:");
difference.print();
Matrix product = matrix1.multiply(matrix2);
System.out.println("Product:");
product.print();
Matrix transpose = matrix1.transpose();
System.out.println("Transpose:");
transpose.print();
}
```
阅读全文