简单矩阵相乘和矩阵置换

import java.util.ArrayList;
import java.util.List;

public class Test {

	public static void main(String[] args) {
		int a[][] = {{3,4,5},{1,2,3}};
		int b[][] = {{2,7,1,3},{2,1,2,4},{1,6,2,1}};
		resultOut(matrixMultiplication(a, b));
		resultOut(maxtrixPermutation(a));
		resultOut(maxtrixPermutation(b));
	}
	
	//矩阵相乘(行乘以列)
	public static int[][] matrixMultiplication(int a[][],int b[][]){
		//a的列数要与b的行数相同
		if(a[0].length!=b.length){
			return null;
		}
		//得到两矩阵相乘后的新矩阵的行列
		int aLength = a.length;
		int bLength = b[0].length;
		List<Integer> list = new ArrayList<Integer>();
		//返回相乘后的数组
		int newArray[][] = new int[aLength][bLength];
		//相当于a行*b列
		int totalLength = aLength * bLength;
		int m = 0,k = 0;
		//最外层循环用于生成矩阵
		for (int i = 0; i < totalLength; i++) {
			//一共计算a*b次结果,每次计算后都要将其结果清零
			int result = 0;
			//矩阵相乘核心计算方式
			for (int n = 0; n < b.length; n++) {
				result += a[m][n] * b[n][k];
			}
			k++;
			if((i+1)%bLength==0){
				m++;
				k=0;
			}
			list.add(result);
		}
		//下面这些只是为了统一输出,可有可无
		int count = 0;
		for (int i = 0; i < newArray.length; i++) {
			for (int j = 0; j < newArray[i].length; j++) {
				newArray[i][j] = list.get(count);
				count++;
			}
		}
		return newArray;
	}
	
	//矩阵置换(行列置换)
	public static int[][] maxtrixPermutation(int beforeArray[][]){
		int column = beforeArray[0].length;
		int row = beforeArray.length;
		int newArray[][] = new int[column][row];
		for (int i = 0; i < newArray.length; i++) {
			for (int j = 0; j < newArray[i].length; j++) {
				newArray[i][j] = beforeArray[j][i];
			}
		}
		return newArray;
	}
	
	//结果输出
	public static void resultOut(int array[][]){
		for (int i = 0; i < array.length; i++) {
			for (int j = 0; j < array[i].length; j++) {
				System.out.print(array[i][j]+" ");
			}
			System.out.println();
		}
	}
	
}

你可能感兴趣的:(java)