C++中检验矩阵是否对称的程序
在线性代数中,当且仅当矩阵的转置等于矩阵本身时,矩阵 M[][]才被称为对称矩阵。矩阵的转置是指沿着对角线翻转矩阵,这会导致矩阵的行和列索引互换。
以下是对称矩阵示例 −
$$\begin{bmatrix} 1 & 4 & 7 \ 4 & 5 & 6 \ 7 & 6 & 9 \ \end {bmatrix} \Rightarrow \begin{bmatrix} 1 & 4 & 7 \ 4 & 5 & 6 \ 7 & 6 & 9 \ \end{bmatrix}$$
上面的矩阵是对称矩阵,我们取矩阵中左侧的矩阵进行转置,结果与矩阵自身相等。
示例
Input: arr1[][n] = { { 1, 2, 3 },
{ 2, 2, 4 },
{ 3, 4, 1 } };
Output: its a symmetric matrix
Input: arr1[][n] = { { 1, 7, 3 },
{ 2, 9, 5 },
{ 4, 6, 8 } };
Output: its not a symmetric matrix 方法
我们可以遵循以下步骤 −
- 1. 取一个矩阵,并将其转置存储在另一个矩阵中。
- 2. 检查生成矩阵是否与输入矩阵相同。
算法
Start
Step 1 -> define macro as #define n 10
Step 2 -> declare function to find transporse of a matrix
void transpose(int arr1[][n], int arr2[][n], int a)
Loop For int i = 0 and i < a and i++
Loop For int j = 0 and j < a and j++
Set arr2[i][j] = arr1[j][i]
End
End
Step 3 -> declare function to check symmetric or not
bool check(int arr1[][n], int a)
declare variable as int arr2[a][n]
Call transpose(arr1, arr2, a)
Loop For int i = 0 and i < a and i++
Loop For int j = 0 and j < a and j++
IF (arr1[i][j] != arr2[i][j])
return false
End
End
End
Return true
Step 4 -> In main()
Declare variable as int arr1[][n] = { { 1, 2, 3 },
{ 2, 2, 4 },
{ 3, 4, 1 } }
IF (check(arr1, 3))
Print its a symmetric matrix
Else
Print its not a symmetric matrix
Stop示例
#include <iostream>
#define n 10
using namespace std;
//find transporse of a matrix
void transpose(int arr1[][n], int arr2[][n], int a){
for (int i = 0; i < a; i++)
for (int j = 0; j < a; j++)
arr2[i][j] = arr1[j][i];
}
//check symmetric or not
bool check(int arr1[][n], int a){
int arr2[a][n];
transpose(arr1, arr2, a);
for (int i = 0; i < a; i++)
for (int j = 0; j < a; j++)
if (arr1[i][j] != arr2[i][j])
return false;
return true;
}
int main(){
int arr1[][n] = { { 1, 2, 3 },
{ 2, 2, 4 },
{ 3, 4, 1 } };
if (check(arr1, 3))
cout << "its a symmetric matrix";
else
cout << "its not a symmetric matrix";
return 0;
}输出
its a symmetric matrix
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言
C++
C#
MongoDB
MySQL
Javascript
PHP