kron.js 2.5 KB

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