Last active
December 11, 2024 17:21
-
-
Save jeroen/36fe3bbf12d430f80852dfe6b6ddf0d1 to your computer and use it in GitHub Desktop.
Example of FFT in R (because I always forget)
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
# Sampling frequency and audio length | |
freq <- 400 | |
duration <- 5 | |
# radian constant for sin/cos | |
tau <- 2*pi | |
# Generate a composite signal (4, 6, 9 hz) | |
x <- seq(0, duration, length.out = freq*duration) | |
y <- | |
1.5 * sin(4 * tau * x) + | |
2.5 * sin(6 * tau * x) + | |
1.2 * cos(9 * tau * x) | |
plot(x,y, type = 'l') | |
# Perform FFT and drop 2nd half | |
fx <- fft(y) | |
fx <- head(fx, length(y)/2) | |
# List the strongest signals (yields back 4, 6, 9hz with amplitude) | |
df <- tibble::tibble( | |
freq = (seq_along(fx)-1)/duration, | |
energy = Mod(fx) / length(fx), | |
) | |
dplyr::arrange(df, desc(energy)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment