JavaScript: Returns n rows by n columns identity matrix
JavaScript Function: Exercise-10 with Solution
Generate Identity Matrix
Write a JavaScript function which returns the n rows by n columns identity matrix.
Pictorial Presentation:

Sample Solution-1:
JavaScript Code:
Output:
1 0 0 0 ---------- 0 1 0 0 ---------- 0 0 1 0 ---------- 0 0 0 1 ----------
Flowchart:

Live Demo:
Sample Solution-2:
JavaScript Code:
Output:
[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]
Explanation:
The above function first creates an empty matrix array “imatrix“ to hold the identity matrix. It then loops through n times to create n rows and columns. In each row, the array is created empty, and then the loop is repeated n times to create each column. For each column, it checks if the row index i is equal to the column index j. If i and j are equal, it pushes a 1 to the row array, otherwise it pushes a 0. After completing the row, it pushes the row array to the matrix array. Upon creating all rows and columns, the function returns the matrix array representing the identity matrix.
Flowchart:

Live Demo:
For more Practice: Solve these Related Problems:
- Write a JavaScript function that generates an n x n identity matrix using nested loops.
- Write a JavaScript function that creates an identity matrix recursively for a given size n.
- Write a JavaScript function that constructs an identity matrix and then transposes it to verify its properties.
- Write a JavaScript function that returns a two-dimensional array representing the identity matrix without using built-in array methods.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function which accepts an argument and returns the type.
Next: Write a JavaScript function which will take an array of numbers stored and find the second lowest and second greatest numbers, respectively.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.