Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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 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
