Construct an identity matrix of order n in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
   ]
]
raja
Published on 11-Dec-2020 14:17:26
Advertisements