个N阶矩阵划成上三角矩阵 JAVA
public class Matrix
{
double [][] matrix;
int length;
//构造函数,初始化矩阵
public Matrix(double [][] ematrix)
{
this.length = ematrix.length;
this.matrix = new double[this.length][this.length];
this.matrix = ematrix;
}
//上三角化,采用消元法,逐行逐行的消
double [][] upTriangular(double [][] ematrix)
{
double [][] 携兄upmatrix;
double [][] submatrix;
int elength = ematrix.length;
int i,j,nums;
double value,value1;
upmatrix = new double[elength][elength];
upmatrix = ematrix;
nums = 1;
while(nums < elength)
{
i = nums - 1;
value = 0;
while(value==0 && i < elength)
{
value = ematrix[i][nums-1];
i = i + 1;
}
if(i > nums && value != 0)
{
for(j = nums - 1; j<elength;j++)
{
upmatrix[0][j] = ematrix[i-1][j];
upmatrix[i-1][j] = ematrix[0][j];
}
}
else if(value != 0)
{
for(i = nums;i<elength;i++)
{
value1 = upmatrix[i][nums-1];
for(j=nums - 1;j<elength;j++)
{
if( value1!=0)
upmatrix[i][j] = upmatrix[i][j]- upmatrix[nums-1][j]*value1/value;
}
}
}
nums = nums + 1;
}
return upmatrix;
}
//显示矩阵
迹隐中public void showMatrix(double [][] ematrix)
{
for(int i = 0; i < ematrix.length ; i++)
{
for(int j =0;j< ematrix.length;j++)
System.out.print(ematrix[i][j] + " ");
System.out.println(" ");
}
}
//测试
姿山public static void main(String [] args)
{
double [][] ematrix = new double[4][4];
double [][] upmatrix = new double[4][4];
for(int i = 0; i < ematrix.length ; i++)
{
for(int j =0;j< ematrix.length;j++)
ematrix[i][j]= (int)(Math.random()*100)+1;
}
for(int i = 0; i < 4 ; i++)
{
for(int j =0;j< 4;j++)
System.out.print(ematrix[i][j] + " ");
System.out.println(" ");
}
System.out.println(" ");
Matrix matrix = new Matrix(ematrix);
upmatrix = matrix.upTriangular(matrix.matrix);
System.out.println(" ");
matrix.showMatrix(upmatrix);
}
}
测试结果如图: