Java实现的求逆矩阵算法示例

本文实例讲述了Java实现的求逆矩阵算法。分享给大家供大家参考,具体如下:

package demo;

public class MatrixInverse {

public static double Det(double [][]Matrix,int N)//计算n阶行列式(N=n-1)

{

int T0;

int T1;

int T2;

double Num;

int Cha;

double [][] B;

if(N>0)

{

Cha=0;

B=new double[N][N];

Num=0;

if(N==1)

{

return Matrix[0][0]*Matrix[1][1]-Matrix[0][1]*Matrix[1][0];

}

for (T0=0;T0<=N;T0++)//T0循环

{

for (T1=1;T1<=N;T1++)//T1循环

{

for (T2=0;T2<=N-1;T2++)//T2循环

{

if(T2==T0)

{

Cha=1;

}

B[T1-1][T2]=Matrix[T1][T2+Cha];

}

//T2循环

Cha=0;

}

//T1循环

Num=Num+Matrix[0][T0]*Det(B,N-1)*Math.pow((-1),T0);

}

//T0循环

return Num;

} else if(N==0)

{

return Matrix[0][0];

}

return 0;

}

public static double Inverse(double[][]Matrix,int N,double[][]MatrixC){

int T0;

int T1;

int T2;

int T3;

double [][]B;

double Num=0;

int Chay=0;

int Chax=0;

B=new double[N][N];

double add;

add=1/Det(Matrix,N);

for ( T0=0;T0<=N;T0++)

{

for (T3=0;T3<=N;T3++)

{

for (T1=0;T1<=N-1;T1++)

{

if(T1<T0)

{

Chax=0;

} else

{

Chax=1;

}

for (T2=0;T2<=N-1;T2++)

{

if(T2<T3)

{

Chay=0;

} else

{

Chay=1;

}

B[T1][T2]=Matrix[T1+Chax][T2+Chay];

}

//T2循环

}//T1循环

Det(B,N-1);

MatrixC[T3][T0]=Det(B,N-1)*add*(Math.pow(-1, T0+T3));

}

}

return 0;

}

public static void main(String[]args)//测试

{

double[][] TestMatrix = {

{1, 22, 34,22},

{1, 11,5,21} ,

{0,1,5,11},

{7,2,13,19}};

double[][]InMatrix=new double[4][4];

Inverse(TestMatrix,3,InMatrix);

String str=new String("");

for (int i=0;i<4;i++)

{

for (int j=0;j<4;j++)

{

String strr=String.valueOf(InMatrix[i][j]);

str+=strr;

str+=" ";

}

str+="\n";

}

System.out.println("测试结果:");

System.out.println(str);

}

}

运行结果:

以上是 Java实现的求逆矩阵算法示例 的全部内容, 来源链接: utcz.com/p/215730.html

回到顶部