Skip to content

Performance Gains from using TS builtins over writing a mmul and scale from scratch? #23

Description

@bitanath

In utils.ts I rewrote a multiply and scale function in order to create a Variance Covariance matrix in an elegant manner from scratch. This also preserves code for portability in the future to say something like Assemblyscript. However, does it make sense in this case to simply matrix.map(row => row.map((v, i) => v - matrix.reduce((s, r) => s + r[i], 0) / matrix.length)) instead of the O(n^3) that we are doing. Are there significant performance gains from this?

export function multiplyAndScale(a: Matrix, b: Matrix, factor: number): Matrix {
    assertValidMatrices(a, b, "a", "b")
    
    const aRows = a.length;
    const aCols = a[0].length;
    const bCols = b[0].length;

    const flat = new Float64Array(aRows * bCols);
    
    for (let i = 0; i < aRows; i++) {
        for (let k = 0; k < aCols; k++) {
            const aVal = a[i][k] * factor;
            const iOffset = i * bCols;
            for (let j = 0; j < bCols; j++) {
                flat[iOffset + j] += aVal * b[k][j];
            }
        }
    }
    
    const result: Matrix = [];
    for (let i = 0; i < aRows; i++) {
        result[i] = Array.from(flat.subarray(i * bCols, (i + 1) * bCols));
    }
    return result;
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions