Java实现计算矩阵的伴随矩阵、逆矩阵
求伴随矩阵和逆矩阵
基本类代码
Matrix
Phalanx
Matrixs
RowLineFormula
测试
简单使用
由于需要用到行列式的运算与矩阵间的运算的原因,代码会有点多.
首先需要一个及矩阵的类Matrix,命名为Matrix.
import java.util.Arrays;
/**
* @author yiran
* @creat 2021-11-26-13:58
*/
public class Matrix{
// 矩阵
private double[][] matrix;
private int m;
private int n;
public double[][] getMatrix() {
return matrix;
}
public Matrix() {
}
public Matrix(double[][] matrix) {
this.matrix = matrix;
this.m=matrix.length;
this.n=matrix[0].length;
}
public Matrix(int m, int n) {
this.matrix=new double[m][n];
this.m=m;
this.n=n;
}
public void setMatrix(double[][] matrix) {
this.matrix = matrix;
this.m=matrix.length;
this.n=matrix[0].length;
}
public int getM() {
return m;
}
public void setM(int m) {
this.m = m;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
public void print()
{
System.out.println("------------------结果-------------------");
for (int i=0;i<m;i++)
{
for (int j=0;j<n;j++)
{
System.out.print(matrix[i][j]+" ");
}
System.out.println();
}
System.out.println("----------------------------------------");
}
@Override
public String toString() {
return "Matrix{" +
"matrix=" + Arrays.toString(matrix) +
'}';
}
}
还需要一个方阵的Phalanx类(由于求伴随矩阵和逆矩阵的前提是矩阵的方阵).
命名为Phalanx.
/**
* @author yiran
* @creat 2021-11-26-14:01
*/
public class Phalanx extends Matrix {
// 调用父类的构造函数,构造方阵
public Phalanx(int n) {
super(n, n);
}
public Phalanx() {
}
// 初始化方阵,并进行校验
public Phalanx(double[][] matrix) {
if(matrix.length!=matrix[0].length)
{
// 传入参数不符合方阵的要求
System.out.println("初始化失败:传入参数不符合方阵的要求!");
}
else
{
this.setMatrix(matrix);
}
}
public double[][] getPhalanx() {
return getMatrix();
}
public void setPhalanx(double [][] phalanx) {
if(phalanx.length!=phalanx[0].length)
{
// 传入参数不符合方阵的要求
System.out.println("初始化失败:传入参数不符合方阵的要求!");
}
else
{
super.setMatrix(phalanx);
}
}
}
之后是操作矩阵运算的工具类Matrixs.
/**
* 方阵的辅助类
* @author yiran
* @creat 2021-11-26-14:08
*/
public class Matrixs{
// 矩阵转置
public static Matrix reverse(Matrix m)
{
if(m!=null)
{
Matrix new_m=new Matrix();
double[][] m_data = m.getMatrix();
double[][] new_m_data=new double[m.getN()][m.getM()];
for (int i=0;i<m.getN();i++)
{
for (int j=0;j<m.getM();j++)
{
new_m_data[i][j]=m_data[j][i];
}
}
m.setMatrix(new_m_data);
return m;
}
return null;
}
// 矩阵数乘
public static Matrix numtil(Matrix m,double num)
{
if(m!=null)
{
Matrix new_m=new Matrix();
double[][] m_data = m.getMatrix();
double[][] new_m_data=new double[m.getM()][m.getN()];
for (int i=0;i<m.getM();i++)
{
for (int j=0;j<m.getN();j++)
{
new_m_data[i][j] = num * m_data[i][j];
}
}
new_m.setMatrix(new_m_data);
return new_m;
}
return null;
}
/**
*
* @param origin 矩阵数组
* @param i
* @param j
* @return 矩阵对应 i,j 位置的余子式
*/
public static double[][] getLess(double [][] origin,int i,int j)
{
if (origin!=null)
{
int c_i=i-1;
int c_j = j-1;
int n = origin.length;
// 取出余子式
double[