matlab matrix multiplication in javascript

To perform matrix multiplication in JavaScript, similar to MATLAB, you can use the following approaches:

Using Nested Loops

index.tsx
function matrixMultiply(A, B) {
    if (A[0].length !== B.length) {
        throw new Error("Matrix dimensions are incompatible for multiplication");
    }

    const result = new Array(A.length).fill(0).map(() => new Array(B[0].length).fill(0));

    for (let i = 0; i < A.length; i++) {
        for (let j = 0; j < B[0].length; j++) {
            for (let k = 0; k < B.length; k++) {
                result[i][j] += A[i][k] * B[k][j];
            }
        }
    }

    return result;
}

// Example usage:
const A = [[1, 2], [3, 4]];
const B = [[5, 6], [7, 8]];
const result = matrixMultiply(A, B);
console.log(result);
622 chars
24 lines

Using a Library (e.g., Math.js)

You can use libraries like Math.js which provides support for matrix operations, including multiplication.

index.tsx
const math = require('mathjs');

// Define the matrices
const A = math.matrix([[1, 2], [3, 4]]);
const B = math.matrix([[5, 6], [7, 8]]);

// Perform matrix multiplication
const result = math.multiply(A, B);

console.log(result);
230 chars
11 lines

Using a More Modern Approach with TypeScript

If you prefer TypeScript or a more modern JavaScript approach, you might structure your code differently, possibly incorporating classes for matrix operations.

index.tsx
class Matrix {
    data;
    rows;
    cols;

    constructor(data) {
        this.data = data;
        this.rows = data.length;
        this.cols = data[0].length;
    }

    multiply(other) {
        if (this.cols !== other.rows) {
            throw new Error("Incompatible dimensions for multiplication");
        }

        const result = new Array(this.rows).fill(0).map(() => new Array(other.cols).fill(0));

        for (let i = 0; i < this.rows; i++) {
            for (let j = 0; j < other.cols; j++) {
                for (let k = 0; k < other.rows; k++) {
                    result[i][j] += this.data[i][k] * other.data[k][j];
                }
            }
        }

        return new Matrix(result);
    }
}

// Example usage:
const A = new Matrix([[1, 2], [3, 4]]);
const B = new Matrix([[5, 6], [7, 8]]);
const result = A.multiply(B);
console.log(result.data);
880 chars
36 lines

Note: The mathjs library needs to be installed via npm (npm install mathjs) for the second example to work.

gistlibby LogSnag