以下只列出相應函數,在主函數調用時輸入普通的二維數組即可返回得數。
1.打印矩陣
public static void Mprint(double[][] m) //打印一個矩陣
{
for(int i=0;i<m.length;i++)
{
for(int j=0;j<m[0].length;j++)
{
System.out.print(m[i][j] + " ");
}
System.out.println("");
}
}
2.矩陣轉置
public static double[][] Trans(double[][] m) //返回轉置矩陣
{
double[][] a = new double[m[0].length][m.length];
for(int i=0;i<m.length;i++)
{
for(int j=0;j<m[0].length;j++)
{
a[j][i] = m[i][j];
}
}
return a;
}
3.矩陣加法
public static double[][] Add(double[][] m,double[][] n) //矩陣加法
{
if(m.length != n.length || m[0].length != n[0].length)
{ System.out.println("錯誤,矩陣違規"); System.exit(0);}
double[][] a = new double[m.length][m[0].length];
for(int i=0;i<m.length;i++)
{
for(int j=0;j<m[0].length;j++)
{
a[i][j] = m[i][j] + n[i][j];
}
}
return a;
}
4.矩陣乘法
public static double[][] Mul(double[][] m,double[][] n) //矩陣乘法
{
double s;
int k;
if(m[0].length != n.length)
{ System.out.println("相乘矩陣不規范"); System.exit (0);}
double[][] a = new double[m.length][n[0].length];
for(int i=0;i<m.length;i++)
{
for(int j=0;j<n[0].length;j++)
{
for(s=0,k=0;k<m[0].length;k++)
{
s = s + m[i][k]*n[k][j];
}
a[i][j] = s;
}
}
return a;
}
5.求矩陣行列式(包括了情況較為特殊的余子式的計算,替換成調用計算余子式的函數也可)
public static double Det(double[][] m) //求行列式
{
if(m.length != m[0].length)
{System.out.println("錯誤,非方陣"); System.exit(0);}
if(m.length == 1) //只有一個元素時直接返回
return m[0][0];
double l;
double det=0;
if(m.length > 2) //參數為矩陣時進行遞歸
{
for(int i=0;i<m.length;i++)
{
l = Math.pow(-1,i); //余子式的系數
double[][] cof = new double[m.length -1][m.length -1];
for(int j=0;j<cof.length ;j++) //構建余子式
{
for(int k=0;k<cof.length;k++)
{
if(j<i)
cof[j][k] = m[k+1][j];
if(j>i)
cof[j][k] = m[k+1][j+1];
}
}
det = det + l*m[0][i]*Det(cof);
}
}
else
return (m[0][0]*m[1][1] - m[0][1]*m[1][0]);
return det;
}
6.計算余子式(相比求行列式函數中包括的部分,此函數更具有一般性)
public static double Cofm(double[][] m,int a,int b) //計算代數余子式
{
double l = Math.pow(-1,a+b);
double[][] res = new double[m.length -1][m.length -1];
for(int i=0;i<res.length;i++)
{
for(int j=0;j<res.length;j++)
{
if(i<a&&j<b)
res[i][j] = m[i][j];
else if(i>=a&&j<b)
res[i][j] = m[i+1][j];
else if(i<a&&j>=b)
res[i][j] = m[i][j+1];
else if(i>=a&&j>=b)
res[i][j] = m[i+1][j+1];
}
} //代數余子式形式的矩陣
return l*Det(res);
}
7.矩陣求逆(注:調用了上面的求余子式的函數和求行列式的函數)
public static double[][] Inv(double[][] m) //求逆矩陣
{
double[][] adj = new double[m.length][m.length];
for(int i=0;i<m.length;i++)
{
for(int j=0;j<m.length;j++)
{
adj[j][i] = Cofm(m,i,j)/Det(m);
}
}
return adj;
}
在主函數調用即可