w3resource

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:

JavaScript: Returns n rows by n columns identity matrix

Sample Solution-1:

JavaScript Code:

// Define a function named matrix that prints a square matrix with diagonal elements set to 1 and others to 0
function matrix(n) {
    // Initialize variables i and j for row and column indices
    var i;
    var j;

    // Iterate through each row
    for (i = 0; i < n; i++) {
        // Iterate through each column
        for (j = 0; j < n; j++) {
            // Check if the current position is on the diagonal (i equals j)
            if (i === j) {
                // Print 1 if on the diagonal
                console.log(' 1 ');
            } else {
                // Print 0 if not on the diagonal
                console.log(' 0 ');
            }
        }
        // Print a line of dashes to separate rows
        console.log('----------');
    }
}

// Call the matrix function with the parameter 4
matrix(4); 

Output:

 1 
 0 
 0 
 0 
----------
 0 
 1 
 0 
 0 
----------
 0 
 0 
 1 
 0 
----------
 0 
 0 
 0 
 1 
----------

Flowchart:

Flowchart: JavaScript function: Returns n rows by n columns identity matrix

Live Demo:

See the Pen JavaScript -Returns n rows by n columns identity matrix-function-ex- 10 by w3resource (@w3resource) on CodePen.


Sample Solution-2:

JavaScript Code:

// Define a function named identity_matrix that generates an identity matrix of size n
function identity_matrix(n) {
  // Initialize an empty array to store the identity matrix
  let imatrix = [];

  // Iterate through each row
  for (let i = 0; i < n; i++) {
    // Initialize an empty array to store the current row
    let row = [];

    // Iterate through each column
    for (let j = 0; j < n; j++) {
      // Check if the current position is on the diagonal (i equals j)
      if (i === j) {
        // If on the diagonal, push 1 to the row
        row.push(1);
      } else {
        // If not on the diagonal, push 0 to the row
        row.push(0);
      }
    }

    // Push the completed row to the identity matrix
    imatrix.push(row);
  }

  // Return the generated identity matrix
  return imatrix;
}

// Log the result of calling identity_matrix with the parameter 4 to the console
console.log(identity_matrix(4)); 

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:

Flowchart: JavaScript function: Returns n rows by n columns identity matrix

Live Demo:

See the Pen javascript-function-exercise-10-1 by w3resource (@w3resource) on CodePen.


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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-function-exercise-10.php