Writing a 2x2 inverse matrix function in JavaScript
Tags: javascript, tutorial, programming
Published: 2022-08-01 18:05:00

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


![2x2 matrix](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/av04nkh42icoho115k72.PNG)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/raxl2szvhrk7gcdn6k80.PNG)


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]`:

```js
let temp = [0][0];
matrix[0][0] = matrix[1][1];
matrix[1][1] = temp;
```

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`.

```js
matrix[0][1] *= -1;
matrix[1][0] *= -1;
```

<b>`a *= -1` is another shorter way of writing `a = a * -1`</b>


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

```js
let determinate = (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);
```

The last step can be done easily multiplying each element by `1/determinate`
```js
matrix[0][0] *= (1/determinate);
matrix[0][1] *= (1/determinate);
matrix[1][0] *= (1/determinate);
matrix[1][1] *= (1/determinate);
```

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

```js
const flatMapped = matrix.flat().map(el => el * 1/determinate);
matrix = [flatMapped.splice(0, 2), flatMapped.splice(0, 2)];
```

* 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`
```js
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
}
```

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

<b>Possible next steps to enhance our function: </b>

* 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:

* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat