-
定义两个矩阵A和B。
-
A = {
{1, 3, 5},
{-3, 6, 0},
{13, -5, 7},
{-2, 19, 25} -
B = {
{0, -1, -2},
{7, -1, 6},
{-6, 13, 2},
{12, -8, -13} -
计算A+B和A-B。
-
计算矩阵A的转置
package com.xy.boda;
public class MatrixOperations {
public static void main(String[] args) {
// 定义矩阵A
int[][] A = {
{1, 3, 5},
{-3, 6, 0},
{13, -5, 7},
{-2, 19, 25}
};
// 定义矩阵B
int[][] B = {
{0, -1, -2},
{7, -1, 6},
{-6, 13, 2},
{12, -8, -13}
};
// 计算A+B
int[][] sum = addMatrices(A, B);
System.out.println("A + B: ");
printMatrix(sum);
// 计算A-B
int[][] difference = subtractMatrices(A, B);
System.out.println("A - B: ");
printMatrix(difference);
// 计算矩阵A的转置
int[][] transposeOfA = transposeMatrix(A);
System.out.println("Transpose of A: ");
printMatrix(transposeOfA);
}
// 矩阵相加的方法
public static int[][] addMatrices(int[][] A, int[][] B) {
int rows = A.length;
int cols = A[0].length;
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = A[i][j] + B[i][j];
}
}
return result;
}
// 矩阵相减的方法
public static int[][] subtractMatrices(int[][] A, int[][] B) {
int rows = A.length;
int cols = A[0].length;
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = A[i][j] - B[i][j];
}
}
return result;
}
// 矩阵转置的方法
public static int[][] transposeMatrix(int[][] A) {
int rows = A.length;
int cols = A[0].length;
int[][] result = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[j][i] = A[i][j];
}
}
return result;
}
// 打印矩阵的方法,方便查看结果
public static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println(); // for each row print a new line character to separate the rows.
}
}