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

时间:2019-05-07 20:59:15

标签: julia fft fftw

我正在尝试在Julia中可视化信号及其频谱。

我发现FFTW软件包为频率提供了FFT和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

我暂时忽略了负频率。

我应该怎么用朱莉娅做那件事?

1 个答案:

答案 0 :(得分:1)

代码中称为fs的不是采样率,而是采样率的倒数:采样周期。

函数fftfreq将采样 rate 作为其第二个参数。由于您给的第二个参数是采样周期,因此函数返回的频率被(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")