0

I hope to inspect the spectral centroid (SC) in my WAV file.

I am using the following MATLAB code to do so:

function C = SpectralCentroid2(signal,windowLength, step, fs)

% function C = SpectralCentroid(signal,windowLength, step, fs)
% 
% This function computes the spectral centroid feature of an audio signal
% ARGUMENTS:
%  - signal: the audio samples
%  - windowLength: the length of the window analysis (in number of samples)
%  - step: the step of the window analysis (in number of samples)
%  - fs: the sampling frequency
% 
% RETURNS:
%  - C: the sequence of the spectral centroid feature
%

signal = signal / max(abs(signal));
curPos = 1;
L = length(signal);
numOfFrames = floor((L-windowLength)/step) + 1;
H = hamming(windowLength);
m = ((fs/(2*windowLength))*[1:windowLength])';
C = zeros(numOfFrames,1);
for (i=1:numOfFrames)
    window = H.*(signal(curPos:curPos+windowLength-1));    
    FFT = (abs(fft(window,2*windowLength)));
    FFT = FFT(1:windowLength);  
    FFT = FFT / max(FFT);
    C(i) = sum(m.*FFT)/sum(FFT);
    if (sum(window.^2)<0.010)
        C(i) = 0.0;
    end
    curPos = curPos + step;
end
C = C / (fs/2);

When I type the 'SpectralCentroid2(366383, 1024, 128, 44100)', MATLAB says:

>> SpectralCentroid2(366383, 1024, 128, 44100)

ans =

   Empty matrix: 0-by-1

I don't know why this problem has occurred.

rayryeng
  • 102,964
  • 22
  • 184
  • 193
Westporch
  • 717
  • 1
  • 7
  • 13
  • 2
    It seems like signal should be an array of numbers, not just a number, Try `1:366383` just as a test – Fantastic Mr Fox Jul 18 '14 at 02:49
  • `>> SpectralCentroid2(1:366383, 1024, 128, 44100)` **Error using .* Matrix dimensions must agree. Error in SpectralCentroid2 (line 24) window = H.*(signal(curPos:curPos+windowLength-1));** Matlab said above error message.. – Westporch Jul 18 '14 at 04:29

1 Answers1

1

The hamming window H is a column vector while the signal is a row vector (that was declared in the comments). Specifically at this line:

window = H.*(signal(curPos:curPos+windowLength-1));    

... which is line 23 in the code, you are trying to point-by-point multiply a column vector by a row vector, which is why the dimensions are incompatible.

To resolve this, make sure your signal is a column vector before you run the code. As such, add this as the first line of your code after the function declaration.

signal = signal(:);  

This ensures your signal is a column vector so you can declare a 1D signal of either a row or column vector and your code will still work.

To summarize, the reason why you get an empty matrix is because your signal only comprised of one point. You need a long signal... at least as long as your window size for this to work.

rayryeng
  • 102,964
  • 22
  • 184
  • 193