reshape.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { reshape as arrayReshape } from '../../utils/array.js';
  2. import { factory } from '../../utils/factory.js';
  3. var name = 'reshape';
  4. var dependencies = ['typed', 'isInteger', 'matrix'];
  5. export var createReshape = /* #__PURE__ */factory(name, dependencies, _ref => {
  6. var {
  7. typed,
  8. isInteger
  9. } = _ref;
  10. /**
  11. * Reshape a multi dimensional array to fit the specified dimensions
  12. *
  13. * Syntax:
  14. *
  15. * math.reshape(x, sizes)
  16. *
  17. * Examples:
  18. *
  19. * math.reshape([1, 2, 3, 4, 5, 6], [2, 3])
  20. * // returns Array [[1, 2, 3], [4, 5, 6]]
  21. *
  22. * math.reshape([[1, 2], [3, 4]], [1, 4])
  23. * // returns Array [[1, 2, 3, 4]]
  24. *
  25. * math.reshape([[1, 2], [3, 4]], [4])
  26. * // returns Array [1, 2, 3, 4]
  27. *
  28. * const x = math.matrix([1, 2, 3, 4, 5, 6, 7, 8])
  29. * math.reshape(x, [2, 2, 2])
  30. * // returns Matrix [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
  31. *
  32. * math.reshape([1, 2, 3, 4], [-1, 2])
  33. * // returns Matrix [[1, 2], [3, 4]]
  34. *
  35. * See also:
  36. *
  37. * size, squeeze, resize
  38. *
  39. * @param {Array | Matrix | *} x Matrix to be reshaped
  40. * @param {number[]} sizes One dimensional array with integral sizes for
  41. * each dimension. One -1 is allowed as wildcard,
  42. * which calculates this dimension automatically.
  43. *
  44. * @return {* | Array | Matrix} A reshaped clone of matrix `x`
  45. *
  46. * @throws {TypeError} If `sizes` does not contain solely integers
  47. * @throws {DimensionError} If the product of the new dimension sizes does
  48. * not equal that of the old ones
  49. */
  50. return typed(name, {
  51. 'Matrix, Array': function MatrixArray(x, sizes) {
  52. return x.reshape(sizes, true);
  53. },
  54. 'Array, Array': function ArrayArray(x, sizes) {
  55. sizes.forEach(function (size) {
  56. if (!isInteger(size)) {
  57. throw new TypeError('Invalid size for dimension: ' + size);
  58. }
  59. });
  60. return arrayReshape(x, sizes);
  61. }
  62. });
  63. });