程序检查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 查找基质的转运
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 检查是否对称
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;
//查找基质的转运
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];
}
//检查是否对称
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