matlab:在for循环中以短时间间隔运行fft以获取数据长度

时间:2016-05-04 15:04:16

标签: matlab for-loop fft

我有一些EEG数据,我想分解成30秒的窗口,并在每个数据窗口上运行快速傅里叶变换。我试图实现一个for循环,并将索引值增加时间窗口中的样本数。当我运行它时,我可以看到(1)这适用于第一个数据窗口,但不适用于其余的数据,因为(我认为)“样本数减去1”导致的元素少于data_fft所需的元素,因此与f没有相同的尺寸,它们都在图中绘制。 (2)我试图通过在窗口中添加样本数来更新索引值,但是在i = 1之后,它在我的工作空间中变为i = 2而不是我希望的i = 7681。我花了很长时间才想弄清楚如何更改它以便它正常工作,所以任何建议都值得赞赏!代码如下。如果我能澄清任何事情,请告诉我。

    data_ch6 = data(:,6); % looking at just 1 electrode

    tmax = 2*60; % total time in sec I want to analyze; just keeping it to 2 minutes for this exercise 
    tmax_window = 30;  %30 sec window
    times = tmax/tmax_window; % number of times fft should be run
    Nsamps = tmax*hdr.SPR; % total # samples in tmax; sample rate is 256 hz
    Nsamps_window = tmax_window*hdr.SPR; % # samples in time window
    f = hdr.SPR*(0:((Nsamps_window-1)/2))/Nsamps_window; % frequency for plotting


    for i = 1:Nsamps;   % need to loop through data in 30 second windows in tmax
        data_fft = abs(fft(data_ch6(i:i+Nsamps_window-1))); %run fft on data window
        data_fft = data_fft(i:((i+Nsamps_window-1)/2)); %discard half the points

        figure
        plot(f, data_fft)
        i = i+Nsamps_window;

    end

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些错误。首先,让我开始说i是变量名称的一个非常差的选择,因为在matlab中它通常代表sqrt{-1}
至于你的代码,我假设你打算在不重叠的情况下执行加窗FFT。

1)你的循环从1变为Nsamps,增量为1.这意味着你每次前进1个样本。换句话说,您有Nsamps_window-1个重叠。如果您对重叠不感兴趣,可以使用i=1:Nsamps_window:Nsamps-Nsamps_window-1

2)data_fft的长度为Nsamps_window,所以我认为你想做的是data_fft = data_fft(1:round(Nsamps_window/2));

3)绘制FFT结果时,我建议使用dB:plot(20*log10(abs(data_fft)));

4)行i = i+Nsamps_window;没有意义,因为i是你的循环变量(它没有效果)。