DEV Community

James L
James L

Posted on • Edited on

Writing a 2x2 inverse matrix function in JavaScript

The steps to calculate the inverse of a 2x2 matrix such as:

2x2 matrix

are:

  1. Swap the upper left and bottom right elements of the matrix
  2. Negate the other two remaining elements
  3. Calculate the determinate using the formula: (ad - bc)
  4. Multiply each element in the matrix by 1 /determinate

So the inverse can be calculated as:

Formula for inverse of 2x2 matrix

To implement as an algorithm, the matrix will be represented as an array of 2 arrays. For example: [[a,b], [c,d]]

The first step is to swap [0][0] and [1][1]:

let temp = [0][0];
matrix[0][0] = matrix[1][1];
matrix[1][1] = temp;
Enter fullscreen mode Exit fullscreen mode

Then for step 2 we need to negate the last remaining elements which are [0][1] and [1][0]. We can negate them by simply multiplying them by -1.

matrix[0][1] *= -1;
matrix[1][0] *= -1;
Enter fullscreen mode Exit fullscreen mode

a *= -1 is another shorter way of writing a = a * -1

Onto calculating the determinate using the formula ad - bc
This step is a simple calculation:

let determinate = (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);
Enter fullscreen mode Exit fullscreen mode

The last step can be done easily multiplying each element by 1/determinate

matrix[0][0] *= (1/determinate);
matrix[0][1] *= (1/determinate);
matrix[1][0] *= (1/determinate);
matrix[1][1] *= (1/determinate);
Enter fullscreen mode Exit fullscreen mode

We can refactor this step into a nicer few statements using the built-in map(), flat() and splice() functions:

const flatMapped = matrix.flat().map(el => el * 1/determinate);
matrix = [flatMapped.splice(0, 2), flatMapped.splice(0, 2)];
Enter fullscreen mode Exit fullscreen mode
  • The first statement flattens the array from eg. [[a,b], [c,d]] to [a,b,c,d] and then multiplies each element by our determinate.

  • The second statement is a bit tricky to understand. The splice() function deletes elements from the array, taking as its first parameter a starting index and an optional delete count as its second parameter, and returns them as an array.

    • In order to get it back into the [[a,b][c,d]] format we call splice() on the first 2 elements (starting at index 0) to remove them and add them to the matrix.
    • However because the first call to splice() has removed elements a and b, only c and d are left (splice() is mutable), we call it again with the same arguments to get the last 2 elements and push them onto the matrix to be returned.

Now we can put all the steps together to create our function calculateInverse

function calculateInverse(matrix) {

    // Step 1 - Swap a and d
    let temp = [0][0];
    matrix[0][0] = matrix[1][1];
    matrix[1][1] = temp;

    // Step 2 - Negate b and c 
    matrix[0][1] *= -1;
    matrix[1][0] *= -1;

    // Step 3 - Calulate determinate
    let determinate = (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);

    // Step 4 - Multiply indices by 1/determinate
    const flatMapped = matrix.flat().map(el => el * 1/determinate);
    matrix = [flatMapped.splice(0, 2), flatMapped.splice(0, 2)];

    return matrix
}
Enter fullscreen mode Exit fullscreen mode

Please note: This function will only work for a 2x2 matrix. There are additional requirements to calculate an inverse of a larger matrix.

Possible next steps to enhance our function:

  • Adding some checks to ensure the argument passed is an array which contains 2 arrays of 2 elements
  • Checking that the elements in the arrays are numbers
  • If the determinate is zero, the index has no inverse, a check could be added for this scenario.
  • Changing the function to allow the matrix indices to be passed as separate arguments (Hint: ...args)
  • Change Step 4 so the original array is not modified (Hint: slice)

Thanks for reading :)

Links:

Top comments (0)