C语言——矩阵转置

矩阵转置的原理:行元素变成列元素,列元素变成行元素

例如:

\begin{bmatrix} 1 &2 &3 &4 \\ 5&6 &7 &8 \\ 9 &10 &11 &12 \end{bmatrix}\rightarrow \begin{bmatrix} 1 &5 &9 \\ 2&6 &10 \\ 3&7 &11 \\ 4&8 &12 \end{bmatrix}

矩阵转置代码 

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

//矩阵转置
double** Matrix_T(double** arr)
{
    if(arr==NULL)exit(-1);
	int row = (int)_msize(arr) / (int)sizeof(double*);
	int col = (int)_msize(*arr) / (int)sizeof(double);
	double** T = (double**)malloc(sizeof(double*) * col);
	int i = 0;
	int j = 0;
	if (T != NULL)
	{
		for (i = 0; i < col; i++)
		{
			T[i] = (double*)malloc(sizeof(double) * row);
		}
	}
	for (i = 0; i < col; i++)
	{
		for (j = 0; j < row; j++)
		{
			T[i][j] = arr[j][i];
		}
	}
	return T;
}

上述代码中:

  • 首先判断传入指针是否为空
  • 然后判断矩阵的维数,这部分在C语言判断矩阵维数中有详细讲解
  • 为转置后的矩阵开辟空间
  • 进行矩阵装置,行列互换传参 

上述方法使用的是malloc开辟的矩阵,该方法相对于用二维数组存储矩阵有以下几种优势:

1)函数传参时不用输入行列,只需传入指针

2)矩阵的大小可以未知,矩阵维数可以更改

3)不需要宏定义,程序可移植性高

malloc开辟矩阵的代码如下:

double** Make_Matrix(int row, int col)
{
	int i, j;
	double** arr = (double**)malloc(sizeof(double*) * row);
	if (arr != NULL)
	{
		for (i = 0; i < row; i++)
		{
			arr[i] = (double*)malloc(sizeof(double) * col);
		}
	}
	return arr;
}

该方法在C语言malloc开辟矩阵中有详细介绍。 

测试:

为了方便测试,再加入初始化矩阵和打印矩阵两个函数

初始化函数 

void Init_Matrix(double** arr)
{
	int i, j;
	int row = (int)_msize(arr) / (int)sizeof(double*);
	int col = (int)_msize(*arr) / (int)sizeof(double);
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			arr[i][j] = pow(i,j);
		}
	}
}

 为了更加直观,让每个元素等于 i 的 j 次方

打印函数 

//打印矩阵
void print(double** arr)
{
	putchar('\n');
	int i, j, row, col;
	row = (int)_msize(arr) / (int)sizeof(double*);
	col = (int)_msize(*arr) / (int)sizeof(double);
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			printf("%8.3lf ", arr[i][j]);
		}
		putchar('\n');
	}
}

主函数测试 

int main()
{
	int i = 3;
	int j = 5;
	double** arr = Make_Matrix(i, j);
	Init_Matrix(arr);
	double** res = Matrix_T(arr);
	printf("原矩阵:>");
	print(arr);
	printf("逆矩阵:>");
	print(res);
	return 0;
}

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
心中带点小风骚的头像心中带点小风骚普通用户
上一篇 2023年12月12日
下一篇 2023年12月12日

相关推荐