เมทริกซ์เอกลักษณ์ (Identity Matrix)
เมทริกซ์เอกลักษณ์คือเมทริกซ์สี่เหลี่ยมจัตุรัส n×n ที่มีค่า 1 ตามแนวทแยงมุม และ 0 ที่อื่นๆ
ตัวอย่าง n=3
[ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]
ตัวอย่างโค้ด
const num = 5;
const constructIdentity = (num = 1) => {
const res = [];
for (let i = 0; i < num; i++) {
if (!res[i]) {
res[i] = [];
}
for (let j = 0; j < num; j++) {
if (i === j) {
res[i][j] = 1;
} else {
res[i][j] = 0;
}
}
}
return res;
};
console.log(constructIdentity(num));
ผลลัพธ์
[ [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] ]
คำอธิบาย
ใช้ nested loop สร้างแถวและคอลัมน์ กำหนดค่า 1 เมื่อ index แถวเท่ากับ index คอลัมน์ (i === j) มิฉะนั้นเป็น 0
เวอร์ชันสั้นๆ: Array.from({length: n}, (_, i) => Array.from({length: n}, (_, j) => i === j ? 1 : 0))