MCPcopy
hub / github.com/trekhleb/javascript-algorithms / dot

Function dot

src/algorithms/math/matrix/Matrix.js:126–153  ·  view source on GitHub ↗
(a, b)

Source from the content-addressed store, hash-verified

124 * @throws {Error}
125 */
126export const dot = (a, b) => {
127 // Validate inputs.
128 validate2D(a);
129 validate2D(b);
130
131 // Check dimensions.
132 const aShape = shape(a);
133 const bShape = shape(b);
134 if (aShape[1] !== bShape[0]) {
135 throw new Error('Matrices have incompatible shape for multiplication');
136 }
137
138 // Perform matrix multiplication.
139 const outputShape = [aShape[0], bShape[1]];
140 const c = zeros(outputShape);
141
142 for (let bCol = 0; bCol < b[0].length; bCol += 1) {
143 for (let aRow = 0; aRow < a.length; aRow += 1) {
144 let cellSum = 0;
145 for (let aCol = 0; aCol < a[aRow].length; aCol += 1) {
146 cellSum += a[aRow][aCol] * b[aCol][bCol];
147 }
148 c[aRow][bCol] = cellSum;
149 }
150 }
151
152 return c;
153};
154
155/**
156 * Transposes the matrix.

Callers

nothing calls this directly

Calls 3

validate2DFunction · 0.85
shapeFunction · 0.85
zerosFunction · 0.85

Tested by

no test coverage detected