@thi.ng/tensors
Version:
0D/1D/2D/3D/4D tensors with extensible polymorphic operations and customizable storage
51 lines (50 loc) • 1.08 kB
JavaScript
import { assert } from "@thi.ng/errors/assert";
import { tensor } from "./tensor.js";
const mulM = (out, a, b) => {
const {
data: adata,
offset: oa,
shape: [sxa, sya],
stride: [txa, tya]
} = a;
const {
data: bdata,
offset: ob,
shape: [sxb, syb],
stride: [txb, tyb]
} = b;
assert(
sya === sxb,
`incompatible matrix shapes, matrix b requires ${sya} rows`
);
if (out == null) {
out = tensor(a.type, [sxa, syb], { storage: a.storage });
}
const {
data: odata,
offset: oo,
shape: [sxo, syo],
stride: [txo, tyo]
} = out;
assert(
sxo === sxa && syo === syb,
`incompatible output matrix shape, expected: [${sxa},${syb}]`
);
let oax, oox, oby, i, j, k, sum;
for (i = 0; i < sxa; i++) {
oox = oo + i * txo;
oax = oa + i * txa;
for (j = 0; j < syb; j++) {
oby = ob + j * tyb;
sum = 0;
for (k = 0; k < sya; k++) {
sum += adata[oax + k * tya] * bdata[oby + k * txb];
}
odata[oox + j * tyo] = sum;
}
}
return out;
};
export {
mulM
};