永发信息网

如何用C语言求一个三阶矩阵的逆矩阵

答案:1  悬赏:30  手机版
解决时间 2021-02-08 00:01
  • 提问者网友:欲望失宠
  • 2021-02-07 08:20
如何用C语言求一个三阶矩阵的逆矩阵
最佳答案
  • 五星知识达人网友:山河有幸埋战骨
  • 2021-02-07 09:01
C语言求任意阶矩阵的逆矩阵程序

#include <malloc.h>
#include <stdio.h>

/// <summary>
/// 求行列式绝对值
/// </summary>
/// <param name="src">输入的矩阵</param>
/// <param name="n">矩阵的阶数</param>
/// <returns>矩阵对应行列式的值</returns>
double mat_det(double *src[], const unsigned n){
if (2 > n) return src[0][0];
int subsize = n - 1;
double **subvet = (double **) malloc(sizeof(double *)*subsize);
for (int i = 0; i < subsize; ++i)
subvet[i] = src[i+1];
double value = mat_det(subvet, subsize) * src[0][subsize] * ((subsize & 1) ? -1 : 1);
for (int i = 0; i < subsize; ++i){
subvet[i] = src[i];
value += mat_det(subvet, subsize)*src[i + 1][subsize] * ((n + i & 1) ? -1 : 1);
}
free(subvet);
return value;
}

/// <summary>
/// 求矩阵指定位置元素代数余子式的值
/// </summary>
/// <param name="src">输入的矩阵</param>
/// <param name="n">矩阵的阶数</param>
/// <param name="x">矩阵指定元素坐标的x值</param>
/// <param name="y">矩阵指定元素坐标的y值</param>
/// <returns>矩阵指定元素对应代数余子式的值</returns>
double mat_minor(double *src[], const unsigned n, const unsigned x, const unsigned y){
double **minmat = (double **) malloc(sizeof(double *)*(n - 1));
for (unsigned i = 0; i<n - 1; ++i){
minmat[i] = (double *) malloc(sizeof(double)*(n - 1));
for (unsigned j = 0; j<n - 1; ++j)
minmat[i][j] = src[i + (i >= x)][j + (j >= y)];
}
double value = mat_det(minmat, n - 1) * (x + y & 1 ? -1 : 1);
for (unsigned i = 0; i<n - 1; ++i)
free(minmat[i]);
free(minmat);
return value;
}

/// <summary>
/// 求矩阵的逆矩阵
/// </summary>
/// <param name="src">输入的矩阵</param>
/// <param name="des">输入的矩阵的逆矩阵</param>
/// <param name="n">矩阵的阶数</param>
void mat_inv(double *src [],double *des[],const unsigned n){
double det = mat_det(src, n); //求矩阵的行列式的值
for (unsigned i = 0; i < n; ++i){
for (unsigned j = 0; j < n; ++j)
des[i][j] = mat_minor(src, n, j, i) / det;
}
}

int main(){
double input[][3] = { { 8, 4, 9 }, { 2, 3, 5 }, { 7, 6, 1 } };
double output[][3] = { { 0 }, { 0 }, { 0 } };
double *src[3],*des[3];
//矩阵须转换为指针数组形式
for (int i = 0; i < 3; ++i){
src[i] = input[i];
des[i] = output[i];
}
mat_inv(src,des,3);
for (int i = 0; i < 3; ++i){
for (int j = 0; j < 3; ++j)
printf("%lf\t", des[i][j]);
printf("\n");
}
return 0;
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯