UNPKG

2.11 kBMarkdownView Raw
1<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
2
3# Function diff
4
5Create a new matrix or array of the difference between elements of the given array
6The optional dim parameter lets you specify the dimension to evaluate the difference of
7If no dimension parameter is passed it is assumed as dimension 0
8
9Dimension is zero-based in javascript and one-based in the parser and can be a number or bignumber
10Arrays must be 'rectangular' meaning arrays like [1, 2]
11If 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
17math.diff(arr)
18math.diff(arr, dim)
19```
20
21### Parameters
22
23Parameter | Type | Description
24--------- | ---- | -----------
25`arr` | Array &#124; Matrix | An array or matrix
26`dim` | number | Dimension
27
28### Returns
29
30Type | Description
31---- | -----------
32Array &#124; Matrix | Difference between array elements in given dimension
33
34
35## Examples
36
37```js
38const arr = [1, 2, 4, 7, 0]
39math.diff(arr) // returns [1, 2, 3, -7] (no dimension passed so 0 is assumed)
40math.diff(math.matrix(arr)) // returns math.matrix([1, 2, 3, -7])
41
42const arr = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [9, 8, 7, 6, 4]]
43math.diff(arr) // returns [[0, 0, 0, 0, 0], [8, 6, 4, 2, -1]]
44math.diff(arr, 0) // returns [[0, 0, 0, 0, 0], [8, 6, 4, 2, -1]]
45math.diff(arr, 1) // returns [[1, 1, 1, 1], [1, 1, 1, 1], [-1, -1, -1, -2]]
46math.diff(arr, math.bignumber(1)) // returns [[1, 1, 1, 1], [1, 1, 1, 1], [-1, -1, -1, -2]]
47
48math.diff(arr, 2) // throws RangeError as arr is 2 dimensional not 3
49math.diff(arr, -1) // throws RangeError as negative dimensions are not allowed
50
51// These will all produce the same result
52math.diff([[1, 2], [3, 4]])
53math.diff([math.matrix([1, 2]), math.matrix([3, 4])])
54math.diff([[1, 2], math.matrix([3, 4])])
55math.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)