- 矩阵乘法
假设上图为矩阵A*B=C:
那么矩阵C中的元素C[i][j]=矩阵A中的第i行与矩阵B中的第j列,对应位置每个值的乘积之和。
这句话是矩阵乘法的核心。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[][] A = new int[n][n];
int[][] B = new int[n][n];
int[][] C = new int[n][n];
for (int i = 0; i < n; i++) {// 输入矩阵A
for (int j = 0; j < n; j++) {
A[i][j] = in.nextInt();
}
}
for (int i = 0; i < n; i++) {// 输入矩阵B
for (int j = 0; j < n; j++) {
B[i][j] = in.nextInt();
}
}
for (int i = 0; i < n; i++) {// c1的行
for (int j = 0; j < n; j++) {// c2的列
for (int k = 0; k < n; k++) {// k代表矩阵A的列的同时也代表矩阵B的行
C[i][j] += A[i][k] * B[k][j];// 计算矩阵C
}
}
}
for (int i = 0; i < n; i++) {// 打印矩阵C
for (int j = 0; j < n; j++) {
System.out.print(C[i][j] + " ");
}
System.out.println("");
}
}
}
总结出模板套用:
package ACM_数学;
import java.util.Scanner;
public class text {
static int[][] pow2(int A[][], int B[][]) {
int C[][] = new int[A.length][B.length];
for (int i = 0; i < C.length; i++) {// 初始化
for (int j = 0; j < C[0].length; j++) {
C[i][j] = 0;
}
}
for (int i = 0; i < A.length; i++) {// i矩阵A的行
for (int j = 0; j < B[0].length; j++) {// j矩阵B的列
for (int k = 0; k < A.length; k++) {// k代表矩阵A的列的同时也代表矩阵B的行
C[i][j] += A[i][k] * B[k][j];
}
}
}
return C;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[][] A = new int[n][n];
int[][] B = new int[n][n];
int[][] C = new int[n][n];
for (int i = 0; i < n; i++) {// 输入矩阵A
for (int j = 0; j < n; j++) {
A[i][j] = in.nextInt();
}
}
for (int i = 0; i < n; i++) {// 输入矩阵B
for (int j = 0; j < n; j++) {
B[i][j] = in.nextInt();
}
}
C = pow2(A, B);
for (int i = 0; i < n; i++) {// 打印矩阵C
for (int j = 0; j < n; j++) {
System.out.print(C[i][j] + " ");
}
System.out.println("");
}
}
}