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 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Suchithra K S
am 3 Mai 2019
Bearbeitet: KALYAN ACHARJYA
am 3 Mai 2019
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 Kommentare
Akzeptierte Antwort
KALYAN ACHARJYA
am 3 Mai 2019
Bearbeitet: KALYAN ACHARJYA
am 3 Mai 2019
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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Simulation, Tuning, and Visualization finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!