I’m trying to write an .m file to extract energy features from an audio track but I seem to be having trouble in its implementation:
% Formula for calculating RMS
[f, fs, nb] = wavread('Three.wav');
frameWidth=441; %10ms
numSamples=length(x);
numFrames=(numSamples/1);
energy(frame)=0;
for frame=1:numFrames,
startSample=(frame-1)*frameWidth+1;
endSample=startSample+frameWidth-1;
% Calculate frame energy
for i=startSample:endSample
energy(frame)=energy(frame)+x(i)^2;
end
end
I run that file in MATLAB and get the following error:
??? Attempted to access x(2); index out of bounds because numel(x)=1.
Error in ==> myrms at 12
energy(frame)=energy(frame)+x(i)^2;
Any help would be much appreciated.
You should be using
finstead ofx, sincefis the actual signal loaded from your .wav file. The variablexwas probably just some other scalar in your workspace, which is why you were getting the error you saw.There are a few other corrections/improvements that should be made to your code. First, as Paul R pointed out, you need to correct how you compute
numFrames. Second,energyshould be initialized as a vector of zeroes. Third, you can reduce the inner for loop to a one-line vectorized operation.Here’s how I would rewrite your code (EDIT: Based on comments, I have updated the code to save a few extra variables computed in the loop):