/*****************************
 * 自定义矩阵类，用于计算方形矩阵求逆
 * add by yxb
 * 2021-12-14
 ****************************/
package com.njcn.utils.sagDomain;

public class Matrix {

    ///   <summary>
    ///   矩阵的逆矩阵
    ///   </summary>
    ///   <param   name= "iMatrix "> </param>
    public static Complex[][] Inverse(Complex[][] iMatrix)
    {
        Complex zero_Cmp =new Complex(0,0);//实部为0的复数
        Complex one_Cmp =new Complex(1,0);//实部为1的复数
        int row = iMatrix[0].length;//获取矩阵的长度
        Complex[][] MatrixZwei = new Complex[row][row * 2];
        //默认初始值为0
        for(int i = 0; i < row; i++){
            for(int j = 0; j < row * 2; j++){
                MatrixZwei[i][j] = zero_Cmp;
            }
        }
        Complex[][] iMatrixInv = new Complex[row][row];
        //默认初始值为0
        for(int i = 0; i < row; i++){
            for(int j = 0; j < row; j++){
                iMatrixInv[i][j] = zero_Cmp;
            }
        }

        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < row; j++)
            {
                MatrixZwei[i][j] = iMatrix[i][j];
            }
        }
        for (int i = 0; i < row; i++)
        {
            for (int j = row; j < row * 2; j++)
            {
                MatrixZwei[i][j] = zero_Cmp;
                if (i + row == j)
                    MatrixZwei[i][j] = one_Cmp;
            }
        }

        for (int i = 0; i < row; i++)
        {
            if (MatrixZwei[i][i] != zero_Cmp)
            {
                Complex intTemp = MatrixZwei[i][i];
                for (int j = 0; j < row * 2; j++)
                {
                    MatrixZwei[i][j] = zero_Cmp.dividion(MatrixZwei[i][j],intTemp);
                }
            }
            for (int j = 0; j < row; j++)
            {
                if (j == i)
                    continue;
                Complex intTemp = MatrixZwei[j][i];
                for (int k = 0; k < row * 2; k++)
                {
                    MatrixZwei[j][k] =zero_Cmp.subduction(MatrixZwei[j][k],zero_Cmp.multiplication(MatrixZwei[i][k],intTemp));
                }
            }
        }

        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < row; j++)
            {
                iMatrixInv[i][j] = MatrixZwei[i][j + row];
            }
        }
        return iMatrixInv;
    }
}
