Calculating the Difference of Arrays in Julia
Overview
In Julia, the diff()
function is provided to calculate differences1. It’s also possible to use the circshift()
function to easily create a similar effect, but dealing with end points and such can be somewhat inconvenient, so knowing how to use diff()
can be much more comfortable. It can be used almost in the same way as the diff()
functions in R and MATLAB, however, unlike these, Julia does not specifically implement second-order differences (calculating the difference twice).
Code
Basic Usage
julia> x = rand(0:9, 12)
12-element Vector{Int64}:
3
1
9
7
1
0
6
5
3
2
9
9
For example, with an array like the one above, simply applying diff()
calculates the difference between preceding and following elements, resulting in the output below. Notice that the size of the array has decreased by exactly 1.
julia> diff(x)
11-element Vector{Int64}:
-2
8
-2
-6
-1
6
-1
-2
-1
7
0
Multidimensional Arrays
julia> X = reshape(x, 3, :)
3×4 Matrix{Int64}:
3 7 6 2
1 1 5 9
9 0 3 9
julia> diff(X)
ERROR: UndefKeywordError: keyword argument dims not assigned
Stacktrace:
[1] diff(a::Matrix{Int64})
@ Base .\multidimensional.jl:997
[2] top-level scope
@ c:\Users\rmsms\OneDrive\lab\DataDrivenModel\REPL.jl:7
For instance, if you have a multidimensional array like the one above, applying diff()
directly will result in an error. This is because the direction in which to compute the difference is not specified. As in the one-dimensional case, you must specify the dims
argument to determine in which dimension to calculate the difference. Pay attention to the fact that the length decreases by one in the direction in which the difference was taken.
julia> diff(X, dims = 1)
2×4 Matrix{Int64}:
-2 -6 -1 7
8 -1 -2 0
julia> diff(X, dims = 2)
3×3 Matrix{Int64}:
4 -1 -4
0 4 4
-9 3 6
Complete Code
x = rand(0:9, 12)
diff(x)
X = reshape(x, 3, :)
diff(X)
diff(X, dims = 1)
diff(X, dims = 2)
Environment
- OS: Windows
- julia: v1.8.5