
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 ] ]
- Related Articles
- Python Program to Print an Identity Matrix
- Golang Program to Print an Identity Matrix
- Swift program to Print an Identity Matrix
- How to create an identity matrix using Numpy?
- Python PyTorch – How to create an Identity Matrix?
- Program for Identity Matrix in C
- Swift program to check if a given square matrix is an Identity Matrix
- How to print a matrix of size n*n in spiral order using C#?
- Check if a Matrix is Identity Matrix or not in Java?
- Retrieving n smallest numbers from an array in their original order in JavaScript
- Matrix creation of n*n in Python
- Construct Turing machine for L = {an bm a(n+m) - n,m≥1} in C++
- Code to construct an object from a string in JavaScript
- Removing n characters from a string in alphabetical order in JavaScript
- Construct ∆PQR in which"\n

Advertisements