diff.md (2166B)
1 <!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. --> 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 ### Throws 36 37 Type | Description 38 ---- | ----------- 39 40 41 ## Examples 42 43 ```js 44 const arr = [1, 2, 4, 7, 0] 45 math.diff(arr) // returns [1, 2, 3, -7] (no dimension passed so 0 is assumed) 46 math.diff(math.matrix(arr)) // returns math.matrix([1, 2, 3, -7]) 47 48 const arr = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [9, 8, 7, 6, 4]] 49 math.diff(arr) // returns [[0, 0, 0, 0, 0], [8, 6, 4, 2, -1]] 50 math.diff(arr, 0) // returns [[0, 0, 0, 0, 0], [8, 6, 4, 2, -1]] 51 math.diff(arr, 1) // returns [[1, 1, 1, 1], [1, 1, 1, 1], [-1, -1, -1, -2]] 52 math.diff(arr, math.bignumber(1)) // returns [[1, 1, 1, 1], [1, 1, 1, 1], [-1, -1, -1, -2]] 53 54 math.diff(arr, 2) // throws RangeError as arr is 2 dimensional not 3 55 math.diff(arr, -1) // throws RangeError as negative dimensions are not allowed 56 57 // These will all produce the same result 58 math.diff([[1, 2], [3, 4]]) 59 math.diff([math.matrix([1, 2]), math.matrix([3, 4])]) 60 math.diff([[1, 2], math.matrix([3, 4])]) 61 math.diff([math.matrix([1, 2]), [3, 4]]) 62 // They do not produce the same result as math.diff(math.matrix([[1, 2], [3, 4]])) as this returns a matrix 63 ``` 64 65 66 ## See also 67 68 [sum](sum.md), 69 [subtract](subtract.md), 70 [partitionSelect](partitionSelect.md)