实验内容:
1、矩阵的转置:设计一个3X4的矩阵C,输入该矩阵,并且输入该矩阵的转置C’
2、实现两个矩阵的乘积(A*B)和点乘(A.*B),示例如下:
第一题代码:
package shiyan4.1;
import java.util.Scanner;
public class Matrix_Transpose {
public static void main(String[] args) {
transpose();
}
public static void transpose () {
Scanner scanner = new Scanner(System.in);
int C[][] = new int[3][4]; //创建一个3*4的矩阵
//利用for循环对二维数组进行赋值
System.out.println("请输入矩阵的值");
for (int i = 0; i < C.length; i++) {
for (int j = 0; j < C[1].length; j++) {
System.out.print("请输入第"+(i+1)+"行,第"+(j+1)+"列的元素:");
C[i][j] = scanner.nextInt();
}
}
//对原矩阵进行输出
System.out.println("矩阵创建成功,原矩阵为:");
for (int i = 0; i < C.length; i++) {
for (int j = 0; j < C[1].length; j++) {
System.out.print(C[i][j] + " ");
}
System.out.println();
}
//对数组进行转置,创建一个新的数组来存放转置后的值
int arr[][] = new int[4][3];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
arr[i][j] = C[j][i];
}
}
//对转置后的矩阵进行输出
System.out.println("矩阵转置成功,转置之后矩阵为:");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
第二题代码:
package Shiyan4.1;
import java.util.Scanner;
public class Matrix_Mul {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入矩阵的行数(列数):");
int num1 = scanner.nextInt();
int arr1[][] = creatMatrix(num1);
int arr2[][] = creatMatrix(num1);
dot_Mul(arr1,arr2);
cross_Mul(arr1,arr2);
}
public static void cross_Mul (int a[][],int b[][]) {
int c [][] = new int[a.length][b.length]; //用来承接两个矩阵的叉乘结果
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
int sum = 0;
for (int k = 0; k < a.length; k++) { //用来计算新的矩阵的结果
sum = sum + a[i][k]*b[k][j];
}
c[i][j] = sum;
}
}
System.out.println("叉乘结果为:");
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < c[1].length; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
public static void dot_Mul (int a[][],int b[][]) {
int c[][] = new int[a.length][b.length]; //用来承接两个矩阵的点乘结果
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
c[i][j] = a[i][j] * b[i][j];
}
}
System.out.println("点乘结果为:");
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < c[1].length; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
public static int[][] creatMatrix (int a) {
Scanner scanner = new Scanner(System.in);
int arr[][] = new int[a][a];
System.out.println("请输入矩阵的值");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[1].length; j++) {
System.out.print("请输入第"+(i+1)+"行,第"+(j+1)+"列的元素:");
arr[i][j] = scanner.nextInt();
}
}
return arr;
}
}
结果示例:略