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    ] ]
Updated on: 2020-12-11T09:47:53+05:30

892 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements