两个类,一个是矩阵对象类Matrix,另一个是测试类MatrixTest
可以实现矩阵创建并巧,赋值,转置,加法,支持行列数不同的矩阵
注1,转置方法将输出一个新的矩阵,并不改变原有矩阵的内容
注2:加法方法是a.add(b),b不发生变化,a发生变化,加法将改变a矩阵的内容,不会产生新矩阵
public class Matrix {
private int rows;
private int columns;
private Integer[][] m;
// 行列构造法
public Matrix(int rows, int columns) {
this.rows = rows;
this.columns = columns;
this.m = new Integer[rows][columns];
}
// 二维数组构造法
public Matrix(Integer[][] m) {
this.m = m;
this.rows = m.length;
this.columns = m[0].length;
}
//察蔽樱 转置
public Matrix exchange() {
Integer[][] result = new Integer[columns][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[j][i] = m[i][j];
}
}
return new Matrix(result);
}
// 加法
public void add(Matrix obj) {
if (obj.getRows() != rows || obj.getColumns() != columns) {
System.out.println("不同行列的矩阵不能相加");
} else {
Integer[][] objarray = obj.toArray();
for (int i = 0; i <败丛 rows; i++) {
for (int j = 0; j < columns; j++) {
m[i][j] += objarray[i][j];
}
}
}
}
// 矩阵赋值
public void setValue(int row, int column, int value) {
if (row < rows && column < columns) {
m[row][column] = value;
} else {
System.out.println("索引超出边界");
}
}
public int getRows() {
return rows;
}
public int getColumns() {
return columns;
}
public Integer[][] toArray() {
return m;
}
public String toString() {
String result = "";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result = result + m[i][j] + " ";
}
result += "\r\n";
}
return result;
}
}
public class MatrixTest {
public static void main(String[] args) {
Matrix m1 = new Matrix(2, 3);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
m1.setValue(i, j, i + j);
}
}
System.out.println(m1.toString());
System.out.println(m1.exchange().toString());
Matrix m2 = new Matrix(2, 3);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
m2.setValue(i, j, (i + 1) * (j + 1));
}
}
System.out.println(m2.toString());
m1.add(m2);
System.out.println(m1.toString());
}
}
1 2 3 3 2 1 4 4 4
4 5 6 + 6 5 4 = 10 10 10
7 8 9 9 8 7 16 16 16
这样肢行吗?你说肢绝的逆转是什么意思?举个例子历饥姿出来。