1、矩阵加法:
package Basic;
/*
*矩阵相关运算:加法,乘法
* */
import java.util.*;
public class matrix {
public static int[][] matrixAdd(int[][] a1 ,int[][] b1){
int[][] c1 = new int[a1.length][b1.length];
for(int i = 0 ; i<c1.length ; i++) {
for(int j = 0 ; j<c1[i].length ; j++) {
c1[i][j] = a1[i][j]+b1[i][j];
}
}
return c1;
}
public static int matrixSum(int[][] matrix) {
int sum = 0;
for(int i=0;i<matrix.length;i++) {
for(int j=0;j<matrix[i].length;j++) {
sum += matrix[i][j];
}
}
return sum;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int n = in.nextInt();//输入是一个几阶矩阵
int a[][] = new int[n][n];
int b[][] = new int[n][n];
//输入a矩阵和b矩阵
for(int i=0;i<a.length;i++) {
for(int j=0;j<a[i].length;j++) {
System.out.println("请输入a矩阵第"+(i+1)+"行"+"第"+(j+1)+"列的数:");
a[i][j] = in.nextInt();
}
}
for(int i=0;i<b.length;i++) {
for(int j=0;j<b[i].length;j++) {
System.out.println("请输入b矩阵第"+(i+1)+"行"+"第"+(j+1)+"列的数:");
b[i][j] = in.nextInt();
}
}
System.out.println("a矩阵为:"+Arrays.deepToString(a));
System.out.println("b矩阵为:"+Arrays.deepToString(b));
//调用两个矩阵相加的函数matrixAdd
System.out.println("矩阵a和矩阵b的和 = "+Arrays.deepToString(matrixAdd(a,b)));
//调用算矩阵所有元素和的函数matrixSum
System.out.println("矩阵a和矩阵b的各个元素之和 = "+matrixSum(matrixAdd(a, b)));
}
}
2、矩阵乘法:
package Basic;
import java.util.Arrays;
/*
* 矩阵相关运算:乘法
* */
import java.util.Scanner;
public class matrixMulti {
public static int[][] matrixMultiplication(int[][] a1,int[][] b1){
//判断矩阵是否可乘:第一个矩阵的列数 = 第二个矩阵的行数
if(a1[0].length != b1.length) {
System.out.println("这两个矩阵不可乘");
return null;
}
else {
int[][] c1 = new int[a1.length][b1[0].length];
for(int i=0 ; i<a1.length ; i++) {
for(int j=0 ; j<a1[i].length ; j++) {
for(int k=0 ; k<b1[i].length ;k++) {
c1[i][j] += a1[i][k] * b1[k][j];
}
}
}
return c1;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int m1 = in.nextInt();//输入矩阵a有几行
int n1 = in.nextInt();//输入矩阵a有几列
int m2 = in.nextInt();//输入矩阵b有几行
int n2 = in.nextInt();//输入矩阵b有几列
int[][] a = new int[m1][n1];
int[][] b = new int[m2][n2];
for(int i=0 ; i<m1 ;i++) {
for(int j=0 ; j<n1 ; j++) {
System.out.println("请输入a矩阵第"+(i+1)+"行"+"第"+(j+1)+"列的数:");
a[i][j] = in.nextInt();
}
}
for(int i=0 ; i<m2 ;i++) {
for(int j=0 ; j<n2 ; j++) {
System.out.println("请输入b矩阵第"+(i+1)+"行"+"第"+(j+1)+"列的数:");
b[i][j] = in.nextInt();
}
}
//输出两个矩阵
System.out.println("a矩阵:"+Arrays.deepToString(a));
System.out.println("b矩阵:"+Arrays.deepToString(b));
//调用matrixMultiplication函数计算两个矩阵相乘的结果
System.out.println("ab = "+Arrays.deepToString(matrixMultiplication(a,b)));
}
}