UNPKG

2.63 kBJavaScriptView Raw
1import { factory } from '../../../utils/factory.js';
2import { DimensionError } from '../../../error/DimensionError.js';
3var name = 'algorithm13';
4var dependencies = ['typed'];
5export var createAlgorithm13 = /* #__PURE__ */factory(name, dependencies, _ref => {
6 var {
7 typed
8 } = _ref;
9
10 /**
11 * Iterates over DenseMatrix items and invokes the callback function f(Aij..z, Bij..z).
12 * Callback function invoked MxN times.
13 *
14 * C(i,j,...z) = f(Aij..z, Bij..z)
15 *
16 * @param {Matrix} a The DenseMatrix instance (A)
17 * @param {Matrix} b The DenseMatrix instance (B)
18 * @param {Function} callback The f(Aij..z,Bij..z) operation to invoke
19 *
20 * @return {Matrix} DenseMatrix (C)
21 *
22 * https://github.com/josdejong/mathjs/pull/346#issuecomment-97658658
23 */
24 return function algorithm13(a, b, callback) {
25 // a arrays
26 var adata = a._data;
27 var asize = a._size;
28 var adt = a._datatype; // b arrays
29
30 var bdata = b._data;
31 var bsize = b._size;
32 var bdt = b._datatype; // c arrays
33
34 var csize = []; // validate dimensions
35
36 if (asize.length !== bsize.length) {
37 throw new DimensionError(asize.length, bsize.length);
38 } // validate each one of the dimension sizes
39
40
41 for (var s = 0; s < asize.length; s++) {
42 // must match
43 if (asize[s] !== bsize[s]) {
44 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
45 } // update dimension in c
46
47
48 csize[s] = asize[s];
49 } // datatype
50
51
52 var dt; // callback signature to use
53
54 var cf = callback; // process data types
55
56 if (typeof adt === 'string' && adt === bdt) {
57 // datatype
58 dt = adt; // callback
59
60 cf = typed.find(callback, [dt, dt]);
61 } // populate cdata, iterate through dimensions
62
63
64 var cdata = csize.length > 0 ? _iterate(cf, 0, csize, csize[0], adata, bdata) : []; // c matrix
65
66 return a.createDenseMatrix({
67 data: cdata,
68 size: csize,
69 datatype: dt
70 });
71 }; // recursive function
72
73 function _iterate(f, level, s, n, av, bv) {
74 // initialize array for this level
75 var cv = []; // check we reach the last level
76
77 if (level === s.length - 1) {
78 // loop arrays in last level
79 for (var i = 0; i < n; i++) {
80 // invoke callback and store value
81 cv[i] = f(av[i], bv[i]);
82 }
83 } else {
84 // iterate current level
85 for (var j = 0; j < n; j++) {
86 // iterate next level
87 cv[j] = _iterate(f, level + 1, s, s[level + 1], av[j], bv[j]);
88 }
89 }
90
91 return cv;
92 }
93});
\No newline at end of file