C#编写的矩阵基本运算

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

public double[,] MatrixTurn(double[,] A)
{
int row = A.GetLength(0); //原矩阵A的行数
int col = A.GetLength(1);
double[,] B = new double[col, row];
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
B[j, i] = A[i, j]; //行、列交换
}
}
return B;
}
///


/// 两个矩阵相乘函数
///

///
///
/// 相乘后的矩阵C
public double[,] MatrixMultiply(double[,] A, double[,] B)
{
int rowA = A.GetLength(0);
int colA = A.GetLength(1);
int rowB = B.GetLength(0);
int colB = B.GetLength(1);
double[,] C = new double[rowA, colB];
try
{
for (int i = 0; i < rowA; i++)
{
for (int j = 0; j < colB; j++)
{
C[i, j] = 0;
for (int k = 0; k < colA; k++)
{
C[i, j] += A[i, k] * B[k, j];
}
}
}
return C;
}
catch
{
System.Exception exp = new Exception("前者矩阵列数不等于后者矩阵行数,不能相乘!");
throw exp;
}
}
///
/// 两个矩阵相加函数
///

///
///
/// 相加后的矩阵C
public double[,] MatrixAdd(double[,] A, double[,] B)
{
int rowA = A.GetLength(0);
int colA = A.GetLength(1);
//int rowB = B.GetLength(0);
//int colB = B.GetLength(1);
double[,] C = new double[rowA, colA];
try
{
for (int i = 0; i < rowA; i++)
{
for (int j = 0; j < colA; j++)
{
C[i, j] = A[i, j] + B[i, j];
}
}
return C;
}
catch
{
System.Exception exp = new Exception("相加的两个矩阵行数或者列数不相等,不能相加!");
throw exp;
}
}
///
/// 两个矩阵相减函数
///

///
///
/// 相减后的矩阵C
public double[,] MatrixSub(double[,] A, double[,] B)
{
int rowA = A.GetLength(0);
in

t colA = A.GetLength(1);
//int rowB = B.GetLength(0);
//int colB = B.GetLength(1);
double[,] C = new double[rowA, colA];
try
{
for (int i = 0; i < rowA; i++)
{
for (int j = 0; j < colA; j++)
{
C[i, j] = A[i, j] - B[i, j];
}
}
return C;
}
catch
{
System.Exception exp = new Exception("相加的两个矩阵行数或者列数不相等,不能相减!");
throw exp;
}
}
///


/// 矩阵求逆
///

///
/// 逆矩阵C
public double[,] MatrixInv(double[,] A)
{
int row=A.GetLength (0);
double[,] B = new double[row, row];
double[,] C = new double[row, row];
int i,j,k;
try
{
for (i = 0; i < row; i++) //clone
{
for (j = 0; j < row; j++)
{
B[i, j] = A[i, j];
}
}
for (i = 0; i < row; i++) //置零
{
for (j = 0; j < row; j++)
{
if (i == j)
{
C[i, j] = 1;
}
else
{
C[i, j] = 0;
}
}
}
//i表示第几行,j表示第几列
for (j = 0; j < row; j++)
{
bool flag = false;
for (i = j; i < row; i++)
{
if (B[i, j] != 0)
{
flag = true;
double temp;
//交换i,j,两行
if (i != j)
{
for (k = 0; k < row; k++)
{
temp = B[j, k];
B[j, k] = B[i, k];
B[i, k] = temp;

temp = C[j, k];
C[j, k] = C[i, k];
C[i, k] = temp;
}
}
//第j行标准化
double d = B[j, j];
for (k = 0; k < row; k++)
{
B[j, k] = B[j, k] / d;

C[j, k] = C[j, k] / d;
}
//消去其他行的第j列
d = B[j, j];
for (k = 0; k < row; k++)
{
if (k != j)
{
double t = B[k, j];
for (int n = 0; n < row; n++)
{
B[k, n] -= (t / d) * B[j, n];
C[k, n] -= (t / d) * C[j, n];
}
}
}
}
}
if (!flag)
return null;
}
return C;
}
catch
{
Exception exp = new Exception("该矩阵不可求逆,检查是否为方阵!");
throw exp;
}
}

相关文档
最新文档