[Edit]
+
0
-
0

JavaScript - multiply two matrixes

548
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
const createMatrix = (width, height, creator = () => 0) => { const result = new Array(height); for (let y = 0; y < height; ++y) { const row = new Array(width); for (let x = 0; x < width; ++x) { row[x] = creator(x, y); } result[y] = row; } return result; }; const findWidth = (matrix) => { if (matrix.length > 0) { const row = matrix[0]; if (row) { return row.length; } } return 0; }; const findHeight = (matrix) => { return matrix.length; }; const multiplyMatrixes = (a, b) => { const length = findWidth(a); if (length !== findHeight(b)) { throw new Error('Matrixes can not be multipled.'); } const width = findWidth(b); const height = findHeight(a); const result = createMatrix(width, height); for (let y = 0; y < height; ++y) { const row = result[y]; for (let x = 0; x < width; ++x) { let value = 0; for (let i = 0; i < length; ++i) { value += a[y][i] * b[i][x]; } row[x] = value; } } return result; }; // Usage example: const a = [ [1, 2], [4, 5], [7, 8] ]; const b = [ [1, 2, 3], [4, 5, 6] ]; const c = multiplyMatrixes(a, b); console.log(c); // Output: // // [ 9, 12, 15], // [24, 33, 42], // [39, 54, 69]
Reset