class Matrix
{
public double[, ] Element { get; set; }
public int Rows { get { return Element.GetLength(0); } }
public int Columns { get { return Element.GetLength(1); } }
//创建索引属性
public double this[int row, int column]
{
get
{
if(row < Rows && column < Columns)
{
return Element[row, column];
}
else
{
System.Exception ex = new Exception("矩阵索引超限");
throw ex;
}
}
set
{
if (row < Rows && column < Columns)
{
Element[row, column] = value;
}
else
{
System.Exception ex = new Exception("矩阵索引超限");
throw ex;
}
}
}
public Matrix(double[,] element)
{
Element = element;
}
/// <summary>
/// 矩阵求逆(初等行变换法)
/// </summary>
/// <returns></returns>
public Matrix Inv()
{
Matrix subMatrix = new Matrix(new double[Rows, Columns * 2]);
Matrix result = new Matrix(new double[Rows, Rows]);
if (Rows != Columns)
{
MessageBox.Show("非方阵无法求逆");
}
else
{
//在矩阵右方增加一同型单位矩阵
for (int i = 0; i < subMatrix.Rows; i++)
{
for (int j = 0; j < subMatrix.Columns; j++)
{
if (j < Columns)
subMatrix[i, j] = Element[i, j];
else
{
if (i == j - Columns)
subMatrix[i, j] = 1;
else
subMatrix[i, j] = 0;
}
}
}
for (int rowThis = 0; rowThis < subMatrix.Rows; rowThis++)
{
//若对角线上元素不为1,则进行一次乘数行变换将其变为1
if (subMatrix[rowThis, rowThis] != 1)
{
double diagElement = subMatrix[rowThis, rowThis];
for (int column = 0; column < subMatrix.Columns; column++)
{
subMatrix[rowThis, column] /= diagElement;
}
}
//遍历其他行,执行其他行减去本行的操作
for (int rowOther = 0; rowOther < subMatrix.Rows; rowOther++)
{
if (rowOther != rowThis)
{
double rowHanlde = subMatrix[rowOther, rowThis];
for (int column = 0; column < subMatrix.Columns; column++)
{
subMatrix[rowOther, column] -=
rowHanlde * subMatrix[rowThis, column]; //其他行减本行
}
}
else
{
continue;
}
}
}
//结果赋值
for (int row = 0; row < Rows; row++)
{
for (int column = 0; column < Columns; column++)
{
result[row, column] = subMatrix[row, Columns + column];
}
}
}
return result;
}
}
运行结果