Created
September 30, 2023 20:42
-
-
Save adamnemecek/cdba6b8f8f7292232a479fb181a351c6 to your computer and use it in GitHub Desktop.
DSP in 20 loc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using LinearAlgebra: diag | |
# returns a `LinRange` representing `k`s which can | |
# be passed into `diag`, starting from top right | |
function diags(m::AbstractMatrix) | |
(nr, nc) = size(m) .- 1 | |
return reverse(-nr:nc) | |
end | |
# sum of values along diagonal, `diagsum(m, 0) == tr(m)` | |
diagsum(m::AbstractMatrix, k::Integer = 0) = sum(diag(m, k)) | |
function xcorr(a::AbstractVector, b::AbstractVector) | |
m = a * b' | |
return diagsum.(Ref(m), diags(m)) | |
end | |
conv(a::AbstractVector, b::AbstractVector) = xcorr(a, reverse(b)) | |
# tests | |
using DSP | |
@assert DSP.xcorr(1:3, 1:5) == xcorr(1:3, 1:5) | |
@assert DSP.conv(1:3, 1:5) == conv(1:3, 1:5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment