package testArray2;
/**
* 练习矩阵,封装矩阵常用算法
* @author Shinelon
*
*/
public class Matrix {
public static void print(int[][] c){
for(int i = 0;i<c.length;i++){
for(int j = 0;j<c.length;j++){
System.out.print(c[i][j]+"\t");
}
System.out.println();
}
System.out.println();
}
//加法
public static int[][] add(int[][] a,int[][] b){
int[][] c = new int [a.length][b[0].length];
for(int i = 0;i<a.length;i++){
for(int j = 0;j<b[0].length;j++){
c[i][j]=a[i][j]+b[i][j];
}
}
return c;
}
//乘法
public static int[][] multiply(int[][] a,int[][] b){
if (a[0].length != b.length)
return null;
int[][] c = new int [a.length][b[0].length];
for(int i = 0;i<a.length;i++){
for(int j = 0;j<b[0].length;j++){
for(int k = 0;k<b.length;k++){
c[i][j] += a[i][k] * b[k][j]; //c[i][j]等于a[i]所在的行分别乘以b[j]所在的列对应值的和
}
}
}
return c;
}
public static void main(String[] args) {
int[][] a = {
{1,3,4},
{2,4,6},
{1,2,3}
};
int[][] b = {
{3,4,2},
{5,6,3},
{2,2,4}
};
print(add(a, b));
int[][] c = {
{1,3},
{2,4},
{1,2}
};
int[][] d = {
{3,4,2},
{5,6,3}
};
print(multiply(c, d));
}
}
结果为
4 7 6
7 10 9
3 4 7
7 10 9
3 4 7
18 22 11
26 32 16
13 16 8
26 32 16
13 16 8