Package Com.yang.matrix; Public classTestmatrix { Public Static voidMain (string[] args) {//test Data//double[][] a={{0.2368,0.2471,0.2568,1.2671},//{1.1161,0.1254,0.1397,0.149},//{0.1582,1.1675,0.1768,0.1871},//{0.1968,0.2071,1.2168,0.2271}}; Double[] a={{1,3,1}, {2,1,1}, {2,2,1} }; Double[] b={{1,3,1}, {2,1,1}, {2,2,1} }; Double[] c=New Double[3][3]; Testmatrix TM=NewTestmatrix (); Tm. MRINV (A,3); //Verify A*a-1=eTm. Mrcheng (A,b,c,3,3,3); Tm. Printmatrix (c,3); } Public Static voidPrintmatrix (Double[] A,intN) { for(intI=0; i<n;i++){ for(intj=0; j<n;j++) {System. out. Print (a[i][j]+" "); } System. out. println (); } } //////////////////////////////////////////////////////////////////////// //function: Mrinv//function: To find the inverse of the matrix//parameters: N---integers, order of matrices//a---Double-n*n two-dimensional array, starting with the original matrix, and returning as the inverse matrix //////////////////////////////////////////////////////////////////////// Public Static voidMRINV (Double[] A,intN) {intI, J, Row, Col, K; DoubleMax, temp; int[] p =New int[n]; Double[] B =New Double[N][n]; for(i =0; I < n; i++) {P[i]=i; B[i][i]=1; } for(k =0; K < n; k++) { //Brahma YuanMax =0; Row= Col =i; for(i = k; i < n; i++) for(j = k; J < N; j + +) {Temp=Math.Abs (B[i][j]); if(Max <temp) {Max=temp; Row=i; Col=J; } } //swap rows and columns to adjust the main element to K row k column if(Row! =k) { for(j =0; J < N; J + +) {Temp=A[row][j]; A[ROW][J]=A[k][j]; A[K][J]=temp; Temp=B[row][j]; B[ROW][J]=B[k][j]; B[K][J]=temp; } I=P[row]; P[row]=P[k]; P[K]=i; } if(Col! =k) { for(i =0; I < n; i++) {Temp=A[i][col]; A[i][col]=A[i][k]; A[I][K]=temp; } } //processing for(j = k +1; J < N; J + +) A[k][j]/=A[k][k]; for(j =0; J < N; J + +) B[k][j]/=A[k][k]; A[K][K]=1; for(j = k +1; J < N; J + +) { for(i =0; I < K; i++) A[i][j]-= a[i][k] *A[k][j]; for(i = k +1; I < n; i++) A[i][j]-= a[i][k] *A[k][j]; } for(j =0; J < N; J + +) { for(i =0; I < K; i++) B[i][j]-= a[i][k] *B[k][j]; for(i = k +1; I < n; i++) B[i][j]-= a[i][k] *B[k][j]; } for(i =0; I < K; i++) A[i][k]=0; A[K][K]=1; } //Restore the order of the ranks; for(j =0; J < N; J + +) for(i =0; I < n; i++) A[p[i]][j]=B[i][j]; } //matrix multiplication Public voidMrcheng (Double[] A,Double[] B,Double[][]c,intMintNintl) {Double[] d=New Double[M][l]; //use intermediate variable D to prevent c=a or c=b calculation errors inti,j,k; for(i=0; i<m;i++) for(j=0; j<l;j++) {D[i][j]=0; for(k=0; k<n;k++) D[i][j]+=a[i][k]*B[k][j]; } for(i=0; i<m;i++) for(j=0; j<l;j++) C[i][j]=D[i][j]; } }
Java matrix inversion