1 |
|
2 |
|
3 | # Function diff
|
4 |
|
5 | Create a new matrix or array of the difference between elements of the given array
|
6 | The optional dim parameter lets you specify the dimension to evaluate the difference of
|
7 | If no dimension parameter is passed it is assumed as dimension 0
|
8 |
|
9 | Dimension is zero-based in javascript and one-based in the parser and can be a number or bignumber
|
10 | Arrays must be 'rectangular' meaning arrays like [1, 2]
|
11 | If something is passed as a matrix it will be returned as a matrix but other than that all matrices are converted to arrays
|
12 |
|
13 |
|
14 | ## Syntax
|
15 |
|
16 | ```js
|
17 | math.diff(arr)
|
18 | math.diff(arr, dim)
|
19 | ```
|
20 |
|
21 | ### Parameters
|
22 |
|
23 | Parameter | Type | Description
|
24 | --------- | ---- | -----------
|
25 | `arr` | Array | Matrix | An array or matrix
|
26 | `dim` | number | Dimension
|
27 |
|
28 | ### Returns
|
29 |
|
30 | Type | Description
|
31 | ---- | -----------
|
32 | Array | Matrix | Difference between array elements in given dimension
|
33 |
|
34 |
|
35 | ## Examples
|
36 |
|
37 | ```js
|
38 | const arr = [1, 2, 4, 7, 0]
|
39 | math.diff(arr) // returns [1, 2, 3, -7] (no dimension passed so 0 is assumed)
|
40 | math.diff(math.matrix(arr)) // returns math.matrix([1, 2, 3, -7])
|
41 |
|
42 | const arr = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [9, 8, 7, 6, 4]]
|
43 | math.diff(arr) // returns [[0, 0, 0, 0, 0], [8, 6, 4, 2, -1]]
|
44 | math.diff(arr, 0) // returns [[0, 0, 0, 0, 0], [8, 6, 4, 2, -1]]
|
45 | math.diff(arr, 1) // returns [[1, 1, 1, 1], [1, 1, 1, 1], [-1, -1, -1, -2]]
|
46 | math.diff(arr, math.bignumber(1)) // returns [[1, 1, 1, 1], [1, 1, 1, 1], [-1, -1, -1, -2]]
|
47 |
|
48 | math.diff(arr, 2) // throws RangeError as arr is 2 dimensional not 3
|
49 | math.diff(arr, -1) // throws RangeError as negative dimensions are not allowed
|
50 |
|
51 | // These will all produce the same result
|
52 | math.diff([[1, 2], [3, 4]])
|
53 | math.diff([math.matrix([1, 2]), math.matrix([3, 4])])
|
54 | math.diff([[1, 2], math.matrix([3, 4])])
|
55 | math.diff([math.matrix([1, 2]), [3, 4]])
|
56 | // They do not produce the same result as math.diff(math.matrix([[1, 2], [3, 4]])) as this returns a matrix
|
57 | ```
|
58 |
|
59 |
|
60 | ## See also
|
61 |
|
62 | [sum](sum.md),
|
63 | [subtract](subtract.md),
|
64 | [partitionSelect](partitionSelect.md)
|