|
矩阵的转置即行列互换。矩阵的加法是对应元素相加。矩阵的乘法是对应行列的点积。
import java.util.Scanner;
public class Main {
//打印矩阵
public static void printMatrix(double[][] matrix,int a,int b){
for(int i=0; i< a; i++){
for(int j=0; j< b; j++){
System.out.printf("%9.5f ",matrix[j]);
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
// Scanner scanner = new Scanner(System.in);
// int a = scanner.nextInt();
// int b = scanner.nextInt();
int a = 3;
int b = 3;
double[][] matrix = new double[][]{{0.84339,0.42034,0.76091},{0.79426,0.89185,0.52491},{0.72037,0.83435,0.36943}};
// while(scanner.hasNext()){
// for(int i=0; i< a; i++){
// for(int j=0; j< b; j++){
// matrix[j] = scanner.nextDouble();
// }
// }
// }
double[][] matrixT = new double[a];//矩阵转置
double[][] matrixA = new double[a];//矩阵加
double[][] matrixP = new double[a];//矩阵乘
//矩阵转置
for(int i=0; i< a; i++){
for(int j=0; j< b; j++){
matrixT[j] = matrix[j];
matrixA[j] = matrix[j] + matrix[j];
}
}
for(int i=0; i< a; i++){
for(int j=0; j< b; j++){
for (int k = 0; k< b; k++) {//columns of a = rows of b
matrixP[j] += matrix[k]*matrixT[k][j];
}
}
}
printMatrix(matrixT,3,3);
printMatrix(matrixA,3,3);
printMatrix(matrixP,3,3);
}
}
C:\test>java Main
0.84339 0.79426 0.72037
0.42034 0.89185 0.83435
0.76091 0.52491 0.36943
1.68678 1.21460 1.48128
1.21460 1.78370 1.35926
1.48128 1.35926 0.73886
1.46698 1.44416 1.23937
1.44416 1.70178 1.51019
1.23937 1.51019 1.35155
矩阵乘法:
public class MultiMatrix {
int[][] multiplyMatrix;
public static void main(String args[]){
int[][] a={{1,0,3,-1},{2,1,0,2}};
int[][] b={{4,1,0},{-1,1,3},{2,0,1},{1,3,4}};
MultiMatrix mm=new MultiMatrix();
mm.mMatrix(a,b);
mm.display();
}
public void mMatrix(int[][] a,int[][] b){
multiplyMatrix=new int[a.length][b[0].length];
for (int i = 0; i< a.length; i++) {//rows of a
for (int j = 0; j< b[0].length; j++) {//columns of b
for (int k = 0; k< a[0].length; k++) {//columns of a = rows of b
multiplyMatrix[j]=multiplyMatrix[j]+a[k]*b[k][j];
}
}
}
}
public void display(){
for (int i = 0; i< multiplyMatrix.length; i++) {
for (int j = 0; j< multiplyMatrix[0].length; j++) {
System.out.print (multiplyMatrix[j]+" ");
}
System.out.println ("");
}
}
} |
|