Matlab:将矩阵正确切成两半以进行信号处理

Matlab: Cut matrix in half correctly for signal processing

我正在研究信号处理 Matlab 项目。我正在执行 FFT 并将矩阵切成两半以仅获得单边频谱。我使用以下代码行并收到错误“警告:用作索引时冒号运算符需要整数操作数 “:

amp = abs(y).^2/n;    % amplitude of the DFT
amp = amp(1:end/2);

为了消除警告,我尝试手动对其进行舍入,但是当我这样做时出现错误“使用舍入时出错 输入参数不足。”

amp = abs(y).^2/n;    % amplitude of the DFT
amp = amp(1:round(end/2));

我想知道的是,对于单边光谱,将矩阵切成两半的正确方法是什么?作为旁注,这是整段代码:

clear all;

% Read Audio
fs = 44100;         % sample frequency (Hz)
full = audioread('song.wav');

% Remove leading 0's and select range
for i = 1:fs
    if full(i) ~= 0
        crop = i;
        break
    end
end
full = full(crop:end);

startTime = 1;
endTime = 5;

% Play song
tic
initialTime = toc;
player = audioplayer(full(fs*startTime:fs*endTime), fs);
player.play();

% Perform fft and get frequencies (hopefully in realish time with audio)
windowSize = fs/16;
for i = windowSize/2+1+fs*(startTime-1) : fs/32 : fs*endTime
    beginningChunk = round(i-windowSize/2);
    endChunk = round(i+windowSize/2);

    x = full(beginningChunk:endChunk);
    y = fft(x);
    n = length(x);     % number of samples in chunk
    amp = abs(y).^2/n;    % amplitude of the DFT
    amp = amp(1:round(end/2));
    f = (0:n-1)*(fs/n);     % frequency range
    f = f(1:round(end/2));
    while initialTime+i/fs > toc
        pause(.0001);
    end
    figure(1);
    plot(f,amp);
    axis([0 10000 0 5]);
    xlabel('Frequency');
    ylabel('amplitude');
end

如果 amp(1:round(end/2)) 对您不起作用(它似乎适用于 R2017a),请改用 amp(1:round(length(amp)/2))。 (或者更好,使用 floor。)

请注意,在这种情况下,end 严格来说是 numel(amp),因为您使用的是线性索引(使用一个值进行索引)。因为amp是向量,所以length也是一样的。

一般情况下,A(end,end),第一端相当于size(A,1),第二端相当于size(A,2)


您可能遇到错误的第二个原因是您有一个名为 round 的自定义函数。在 MATLAB 命令提示符下键入 which round 以找出当您键入 round(1).

时调用的内容