I tried a matlab code for spectral centroid but it showing error like this"Index exceeds matrix dimensions. Error in Untitled2 (line 58) P1i = P2i(1:L/2+1); . How to correct the error?
1 次查看(过去 30 天)
显示 更早的评论
the code is given below,
[audio,fs]=audioread('cryrumble.wav');
frameduration=0.25;
frame_len=frameduration*fs;
N=length(audio);
num_frames=floor(N/frame_len);
for k=1:num_frames
frame=audio( (k-1)*frame_len+1 :frame_len*k);
end
y=fft(frame);
T = 1/fs; % Sampling period
L = length(frame); % Length of signal %%%%% CHANGED %%%%%
t = (0:L-1)*T; % Time vector
P2 = abs(y/L);
P1 = P2(1:L/2+1);
P1(2:end-1) = 2*P1(2:end-1);
f = fs*(0:(L/2))/L;
% Plot overall frequency spectrum %%%%% CHANGED %%%%%
figure
plot(f,P1)
title('Single-Sided Aamplitude Sprecturm for Entire Audio Track')
xlabel('Frequency')
ylabel('Amplitude')
n=250; % length of movin window to calculate spectal centroid in %%%%% CHANGED %%%%%
spec=zeros(1,length(frame)-n); % pre-allocate %%%%% CHANGED %%%%%
fi = Fs*(0:(n/2))/n; % new frequency for fft of length n (Fs doesnt change) %%%%% CHANGED %%%%%
% Loop over audio track with window of length n %%%
for ii=1:length(frame)-n
xi=frame(ii:ii+n-1);
yi=fft(xi);
%%%%% DO THIS %%%%%
% Calculate new "P1i" value based on "yi"
P2i = abs(yi/L);
P1i = P2i(1:L/2+1);
% Use fi and P1i to calculate spec
spec(ii)=sum(fi.*P1i)/sum(P1i);
end
% Plot results
tplot=t(1+round(n/2):L-n+round(n/2)); % center time for spectral centroid window %%%%% CHANGED %%%%%
figure
plot(tplot,spec)
ylabel('Frequency (Hz)')
xlabel('Center of Time Window (seconds)')
0 个评论
采纳的回答
KALYAN ACHARJYA
2019-5-3
编辑:KALYAN ACHARJYA
2019-5-3
Note: The code is tested with different audio file, please check in your case
Line no 28:
Change Fs to fs as Matlab is case sensitive.
Line no 36:
P1i = P2i(1:L/2+1);
Why you getting the error?
whos P2i
Name Size Bytes Class Attributes
P2i 1x250 2000 double
Here P2i is vector
P1i = P2i(1:L/2+1);
P2i(any value) represent the index position of that array.
Here you are trying to fing index elemets of a from 1 to L/2+1, L=11025, therefore
>> L/2+1
ans =
5.5135e+03
Invalid index value,must be positive and real value.
Please find the way out of L/2+1 vlue is positive integer and must be within the range of P2i
Hope it helps!
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Simulation, Tuning, and Visualization 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!