Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

How to inverse N x M matrix in Node.js

1 Answer

0 votes
// matrixUtils.js

// Function to print a matrix
function printMatrix(matrix) {
    const rows = matrix.length;           // number of rows
    const cols = matrix[0].length;        // number of columns

    for (let i = 0; i < rows; i++) {
        let row = '';
        for (let j = 0; j < cols; j++) {
            row += matrix[i][j].toString().padStart(4);
        }
        console.log(row);
    }
}

// Function to invert a matrix (reverse order of elements)
function inverseMatrix(matrix) {
    const rows = matrix.length;
    const cols = matrix[0].length;
    let counter = 0;

    for (let i = 0, r = rows - 1; i < rows; i++, r--) {
        for (let j = 0, c = cols - 1; j < cols; j++, c--) {
            [matrix[i][j], matrix[r][c]] = [matrix[r][c], matrix[i][j]];
            counter++;
            if (counter > (rows * cols) / 2 - 1) return;
        }
    }
}

// Export functions so they can be reused in other files
//module.exports = { printMatrix, inverseMatrix };

// index.js
//const { printMatrix, inverseMatrix } = require('./matrixUtils');

const matrix = [ 
    [1, 2, 3, 4, 18],
    [5, 6, 7, 8, 21],
    [12, 0, 15, 30, 100]
];

console.log('matrix:');
printMatrix(matrix);

inverseMatrix(matrix);

console.log('\ninverse matrix:');
printMatrix(matrix);



/*
run:

matrix:
   1   2   3   4  18
   5   6   7   8  21
  12   0  15  30 100

inverse matrix:
 100  30  15   0  12
  21   8   7   6   5
  18   4   3   2   1
   
*/

 



answered May 17, 2024 by avibootz
edited Nov 23, 2025 by avibootz

Related questions

1 answer 130 views
1 answer 114 views
1 answer 106 views
1 answer 110 views
2 answers 138 views
...