kron.js (2782B)
1 "use strict"; 2 3 Object.defineProperty(exports, "__esModule", { 4 value: true 5 }); 6 exports.createKron = void 0; 7 8 var _array = require("../../utils/array.js"); 9 10 var _factory = require("../../utils/factory.js"); 11 12 var name = 'kron'; 13 var dependencies = ['typed', 'matrix', 'multiplyScalar']; 14 var createKron = /* #__PURE__ */(0, _factory.factory)(name, dependencies, function (_ref) { 15 var typed = _ref.typed, 16 matrix = _ref.matrix, 17 multiplyScalar = _ref.multiplyScalar; 18 19 /** 20 * Calculates the kronecker product of 2 matrices or vectors. 21 * 22 * NOTE: If a one dimensional vector / matrix is given, it will be 23 * wrapped so its two dimensions. 24 * See the examples. 25 * 26 * Syntax: 27 * 28 * math.kron(x, y) 29 * 30 * Examples: 31 * 32 * math.kron([[1, 0], [0, 1]], [[1, 2], [3, 4]]) 33 * // returns [ [ 1, 2, 0, 0 ], [ 3, 4, 0, 0 ], [ 0, 0, 1, 2 ], [ 0, 0, 3, 4 ] ] 34 * 35 * math.kron([1,1], [2,3,4]) 36 * // returns [ [ 2, 3, 4, 2, 3, 4 ] ] 37 * 38 * See also: 39 * 40 * multiply, dot, cross 41 * 42 * @param {Array | Matrix} x First vector 43 * @param {Array | Matrix} y Second vector 44 * @return {Array | Matrix} Returns the kronecker product of `x` and `y` 45 */ 46 return typed(name, { 47 'Matrix, Matrix': function MatrixMatrix(x, y) { 48 return matrix(_kron(x.toArray(), y.toArray())); 49 }, 50 'Matrix, Array': function MatrixArray(x, y) { 51 return matrix(_kron(x.toArray(), y)); 52 }, 53 'Array, Matrix': function ArrayMatrix(x, y) { 54 return matrix(_kron(x, y.toArray())); 55 }, 56 'Array, Array': _kron 57 }); 58 /** 59 * Calculate the kronecker product of two matrices / vectors 60 * @param {Array} a First vector 61 * @param {Array} b Second vector 62 * @returns {Array} Returns the kronecker product of x and y 63 * @private 64 */ 65 66 function _kron(a, b) { 67 // Deal with the dimensions of the matricies. 68 if ((0, _array.arraySize)(a).length === 1) { 69 // Wrap it in a 2D Matrix 70 a = [a]; 71 } 72 73 if ((0, _array.arraySize)(b).length === 1) { 74 // Wrap it in a 2D Matrix 75 b = [b]; 76 } 77 78 if ((0, _array.arraySize)(a).length > 2 || (0, _array.arraySize)(b).length > 2) { 79 throw new RangeError('Vectors with dimensions greater then 2 are not supported expected ' + '(Size x = ' + JSON.stringify(a.length) + ', y = ' + JSON.stringify(b.length) + ')'); 80 } 81 82 var t = []; 83 var r = []; 84 return a.map(function (a) { 85 return b.map(function (b) { 86 r = []; 87 t.push(r); 88 return a.map(function (y) { 89 return b.map(function (x) { 90 return r.push(multiplyScalar(y, x)); 91 }); 92 }); 93 }); 94 }) && t; 95 } 96 }); 97 exports.createKron = createKron;