如何在Julia中可视化一个信号的FFT?

8
我想在Julia中可视化一个信号及其频谱。
我找到了提供FFT的FFTW包和提供频率的DSP包。
这是我正在尝试的,使用正弦信号:
using Plots
using FFTW
using DSP

# Number of points
N = 2^14 - 1
# Sample rate
fs = 1 / (1.1 * N)
# Start time
t0 = 0
tmax = t0 + N * fs

# time coordinate
t = [t0:fs:tmax;]

# signal
signal = sin.(2π * 60 * t)  # sin (2π f t)

# Fourier Transform of it
F = fft(signal)
freqs = fftfreq(length(t), fs)
freqs = fftshift(freqs)

# plots
time_domain = plot(t, signal, title = "Signal")
freq_domain = plot(freqs, abs.(F), title = "Spectrum")
plot(time_domain, freq_domain, layout = 2)
savefig("Wave.pdf")

我本以为会得到一个60 Hz的高峰的漂亮图表,但是结果却很奇怪:

Imgur

我现在忽略负频率。

在Julia中应该如何做到这一点?

1个回答

13
您在代码中称之为fs的内容并不是采样率,而是其倒数:采样周期。
函数fftfreq将采样率作为第二个参数。由于您提供的第二个参数是采样周期,因此该函数返回的频率被错误地缩放了(1/(Ts^2))
我将fs重命名为Ts,将fftfreq的第二个参数更改为采样率1.0/Ts。我认为您还需要对fft的结果进行移位。
# Number of points 
N = 2^14 - 1 
# Sample period
Ts = 1 / (1.1 * N) 
# Start time 
t0 = 0 
tmax = t0 + N * Ts
# time coordinate
t = t0:Ts:tmax

# signal 
signal = sin.(2π * 60 .* t) # sin (2π f t) 

# Fourier Transform of it 
F = fft(signal) |> fftshift
freqs = fftfreq(length(t), 1.0/Ts) |> fftshift

# plots 
time_domain = plot(t, signal, title = "Signal")
freq_domain = plot(freqs, abs.(F), title = "Spectrum", xlim=(-1000, +1000)) 
plot(time_domain, freq_domain, layout = 2)
savefig("Wave.pdf")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接