- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Construct an identity matrix of order n in JavaScript
Identity Matrix
An identity Matrix is a matrix which is n × n square matrix where the diagonal consist of ones and the other elements are all zeros.
For example an identity matrix of order is will be −
const arr = [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ];
We are required to write a JavaScript function that takes in a number, say n, and returns an identity matrix of n*n order.
Example
Following is the code −
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));
Output
Following is the output on console −
[ [ 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 ] ]
Advertisements