📜  身份矩阵的 C++ 程序

📅  最后修改于: 2022-05-13 01:55:50.636000             🧑  作者: Mango

身份矩阵的 C++ 程序

身份矩阵简介:

单位矩阵的字典定义是一个方阵,其中主对角线或主对角线的所有元素都是 1,所有其他元素都是零。在下图中,每个矩阵都是一个单位矩阵。

在线性代数中,这有时被称为单位矩阵,它是一个方阵(大小 = nxn),主对角线上为 1,其他地方为 0。单位矩阵用“ I ”表示。有时 U 或 E 也用于表示单位矩阵。
单位矩阵的一个属性是,如果它与单位矩阵相乘,它会使矩阵保持不变。

例子:

Input  : 2
Output : 1 0
         0 1

Input :  4
Output : 1 0 0 0
         0 1 0 0
         0 0 1 0
         0 0 0 1
The explanation is simple. We need to make all
the elements of principal or main diagonal as 
1 and everything else as 0.

打印身份矩阵的程序:
逻辑很简单。您需要在行等于矩阵列的位置打印 1 并将所有其他位置设为 0。

C++
// C++ program to print Identity Matrix
#include
using namespace std;
  
int Identity(int num)
{
    int row, col;
      
    for (row = 0; row < num; row++)
    {
        for (col = 0; col < num; col++)
        {
            // Checking if row is equal to column 
            if (row == col)
                cout << 1 << " ";
            else
                cout << 0 << " ";
        } 
        cout << endl;
    }
    return 0;
}
  
// Driver Code
int main()
{
    int size = 5;
    Identity(size);
    return 0;
}
  
// This code is contributed by shubhamsingh10


C++
// CPP program to check if a given matrix is identity
#include
using namespace std;
  
const int MAX = 100;
  
bool isIdentity(int mat[][MAX], int N)
{ 
    for (int row = 0; row < N; row++)
    {
        for (int col = 0; col < N; col++)
        {
            if (row == col && mat[row][col] != 1)
                return false;
            else if (row != col && mat[row][col] != 0)
                return false;
        } 
    }
    return true;
}
  
// Driver Code
int main()
{
    int N = 4;
    int mat[][MAX] = {{1, 0, 0, 0}, 
                    {0, 1, 0, 0},
                    {0, 0, 1, 0},
                    {0, 0, 0, 1}}; 
    if (isIdentity(mat, N))
       cout << "Yes ";
    else
       cout << "No ";
    return 0;
}


输出:

1  0  0  0  0  
0  1  0  0  0  
0  0  1  0  0  
0  0  0  1  0  
0  0  0  0  1  


检查给定方阵是否为单位矩阵的程序:

C++

// CPP program to check if a given matrix is identity
#include
using namespace std;
  
const int MAX = 100;
  
bool isIdentity(int mat[][MAX], int N)
{ 
    for (int row = 0; row < N; row++)
    {
        for (int col = 0; col < N; col++)
        {
            if (row == col && mat[row][col] != 1)
                return false;
            else if (row != col && mat[row][col] != 0)
                return false;
        } 
    }
    return true;
}
  
// Driver Code
int main()
{
    int N = 4;
    int mat[][MAX] = {{1, 0, 0, 0}, 
                    {0, 1, 0, 0},
                    {0, 0, 1, 0},
                    {0, 0, 0, 1}}; 
    if (isIdentity(mat, N))
       cout << "Yes ";
    else
       cout << "No ";
    return 0;
}

输出:

Yes