ให้เมทริกซ์สี่เหลี่ยมจัตุรัส M[r][c] โดยที่ 'r' คือจำนวนแถวบางแถวและ 'c' เป็นคอลัมน์ที่ r =c เราต้องตรวจสอบว่า 'M' เป็นเมทริกซ์เอกลักษณ์หรือไม่
เมทริกซ์เอกลักษณ์
เมทริกซ์เอกลักษณ์เรียกอีกอย่างว่าเมทริกซ์หน่วยของขนาดเมทริกซ์สี่เหลี่ยมจัตุรัส nxn โดยที่องค์ประกอบในแนวทแยงจะมีค่าจำนวนเต็มเพียงหนึ่งองค์ประกอบและองค์ประกอบที่ไม่ใช่แนวทแยงจะมีค่าจำนวนเต็มเป็น 0 เท่านั้น
เช่นเดียวกับในตัวอย่างด้านล่าง −
$$I1=\begin{bmatrix}1 \end{bmatrix},\\I2=\begin{bmatrix}1 &0 \\0 &1 \end{bmatrix},\\I3=\begin{bmatrix}1 &0 &0 \\0 &1 &0 \\0 &0 &1 \end{bmatrix},\\In=\begin{bmatrix}
1 &0 &0 &...&0 \\
0 &1 &0 &...&0\\
0 &0 &1 &...&0\\
. &. &. &...&.\\
. &. &. &...&.\\
0 &0 &0 &...&1\\
\end{bmatrix} $$
ตัวอย่าง
Input: m[3][3] = { {1, 0, 0},
{0, 1, 0},
{0, 0, 1}}
Output: yes
Input: m[3][3] == { {3, 0, 1},
{6, 2, 0},
{7, 5, 3} }
Output: no อัลกอริทึม
Start Step 1 -> declare function for finding identity matrix int identity(int num) declare int row, col Loop For row = 0 and row < num and row++ Loop For col = 0 and col < num and col++ IF (row = col) Print 1 Else Print 0 End End Step 2 -> In main() Declare int size = 4 Call identity(size) Stop
ตัวอย่าง
#include<stdio.h>
int identity(int num){
int row, col;
for (row = 0; row < num; row++){
for (col = 0; col < num; col++){
if (row == col)
printf("%d ", 1);
else
printf("%d ", 0);
}
printf("\n");
}
return 0;
}
int main(){
int size = 4;
identity(size);
return 0;
} ผลลัพธ์
1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1