有关求矩阵的行列式和矩阵求逆的问题

doreamon 2003-10-18 08:46:29
我现在需要用c++编一个程序,用来求n阶矩阵的逆,我不知道程序要如何写才合适,总是会碰到一些问题,求矩阵的行列式我就写不出来了,哪位高人可以帮帮忙,谢了

附:我写的matrix类
class Matrix
{
friend istream &operator>>(istream &,Matrix &);
friend ostream &operator<<(ostream &,Matrix &);

private:
int line; //矩阵行数
int row; //矩阵列数
float **mat;

public:
Matrix(int=0,int=0); //默认构造函数
Matrix(int,int,float **);
Matrix(Matrix &); //拷贝构造函数

void getMatrix(); //读取矩阵

Matrix operator+(Matrix &); //矩阵加运算
Matrix operator*(Matrix &); //矩阵乘
Matrix operator=(Matrix &);


};
...全文
393 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ttlb 2003-10-20
  • 打赏
  • 举报
回复
矩阵求逆运算量不大,空间开销也不是很大,不用太在意吧?
doreamon 2003-10-20
  • 打赏
  • 举报
回复
请问矩阵的逆该如何求才节约时间和空间呢
ttlb 2003-10-18
  • 打赏
  • 举报
回复
// 行列式
double Matrix::formulate()
{
Matrix mat(*this);

// 结果
double iResult = 1;

// 从上到下的行变换
for (int i = 0; i < row - 1; ++i)
{
// 如果主对角线上是 0, 则通过行交换使之不为零
if (0 == mat.mat[i][i])
{
for (int m = i + 1; m < mat.row; ++m)
{
if (mat.mat[m][i] != 0)
{
mat.swap_line(i, m);
iResult *= -1;
}
}
// 如果还是 0
if (0 == mat.mat[i][i])
{
return 0;
}
}
// 主对角线上不是 0
else
{
for (int j = i + 1; j < mat.row; ++j)
{
if (0 == mat.mat[j][i])
continue;
// 系数
double dMult = mat.mat[j][i] / mat.mat[i][i];
for (int k = 0; k < line; ++k)
{
mat.mat[j][k] -= mat.mat[i][k] * dMult;
}
}
}
} // for (int i = 0; i < row - 1; ++i), 从上到下的行变换结束
// 计算结果
for (int i = 0; i < mat.row; ++i)
{
iResult *= mat.mat[i][i];
}

return iResult;
}
// 转置
void Matrix::transpose()
{
if (line != row)
{ // row col not equal, must realloc memory
Matrix mat(*this);
release();
create(mat.line, mat.row);
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < line; ++j)
{
mat[i][j] = mat.mat[j][i];
}
}
}
else
{ // row equals col, neednot realloc memory, swap only
for (int i = 0; i < row - 1; ++i)
{
for (int j = i + 1; j < line; ++j)
{
swap(mat[i][j], mat[j][i]);
}
}
}
}

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧