UNPKG

2 kBJavaScriptView Raw
1'use strict'
2
3const array = require('../../utils/array')
4
5function factory (type, config, load, typed) {
6 const matrix = load(require('../../type/matrix/function/matrix'))
7 const isInteger = load(require('../utils/isInteger'))
8
9 /**
10 * Reshape a multi dimensional array to fit the specified dimensions
11 *
12 * Syntax:
13 *
14 * math.reshape(x, sizes)
15 *
16 * Examples:
17 *
18 * math.reshape([1, 2, 3, 4, 5, 6], [2, 3])
19 * // returns Array [[1, 2, 3], [4, 5, 6]]
20 *
21 * math.reshape([[1, 2], [3, 4]], [1, 4])
22 * // returns Array [[1, 2, 3, 4]]
23 *
24 * math.reshape([[1, 2], [3, 4]], [4])
25 * // returns Array [1, 2, 3, 4]
26 *
27 * const x = math.matrix([1, 2, 3, 4, 5, 6, 7, 8])
28 * math.reshape(x, [2, 2, 2])
29 * // returns Matrix [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
30 *
31 * See also:
32 *
33 * size, squeeze, resize
34 *
35 * @param {Array | Matrix | *} x Matrix to be reshaped
36 * @param {number[]} sizes One dimensional array with integral sizes for
37 * each dimension
38 *
39 * @return {* | Array | Matrix} A reshaped clone of matrix `x`
40 *
41 * @throws {TypeError} If `sizes` does not contain solely integers
42 * @throws {DimensionError} If the product of the new dimension sizes does
43 * not equal that of the old ones
44 */
45 const reshape = typed('reshape', {
46
47 'Matrix, Array': function (x, sizes) {
48 if (x.reshape) {
49 return x.reshape(sizes)
50 } else {
51 return matrix(array.reshape(x.valueOf(), sizes))
52 }
53 },
54
55 'Array, Array': function (x, sizes) {
56 sizes.forEach(function (size) {
57 if (!isInteger(size)) {
58 throw new TypeError('Invalid size for dimension: ' + size)
59 }
60 })
61 return array.reshape(x, sizes)
62 }
63
64 })
65
66 reshape.toTex = undefined // use default template
67
68 return reshape
69}
70
71exports.name = 'reshape'
72exports.factory = factory