简体   繁体   中英

Why is my MATLAB code printing every value within the for loop?

I have code that breaks up a sound file into 1 sec chunks, calculates the RMS of the chunk, then plots all chunks. It works fine until I edited it to make it read through a folder rather than one user loaded file at at time. Now it prints every value of fs (all 32k) which obviously massively slows down the script. Here is the new script:

DirIn = 'D:\Trial'
eval(['filelist=dir(''' DirIn '/*.wav'')']) 


for i = 1:length(filelist)
[y,fs] = audioread(strcat(DirIn,'/',filelist(i).name))
npts = length(y);
chunkDur = 1; % length of chunk to analyze in seconds

systemCal = 0; % this should be whatever dB corresponds to an amplitude of 1 in wav file


chunkPts = fs * chunkDur;
rms = [];

for i = 1:chunkPts:npts-chunkPts
    chunkRMS = 20 * log10(std(y(i: i + chunkPts))) + systemCal; % rms of chunk in dB
    rms = [rms; chunkRMS];
end

t = [0: length(rms) - 1] * chunkDur; % time scale
plot(t, rms)
xlabel('Time (s)');
ylabel('RMS dB');
end

For reference, here's the original that works:

npts = length(data);
chunkDur = 1; % length of chunk to analyze in seconds

systemCal = 0; % this should be whatever dB corresponds to an amplitude of 1 in wav file


chunkPts = fs * chunkDur;
rms = [];

for i = 1:chunkPts:npts-chunkPts
    chunkRMS = 20 * log10(std(data(i: i + chunkPts))) + systemCal; % rms of chunk in dB
    rms = [rms; chunkRMS];
end

t = [0: length(rms) - 1] * chunkDur; % time scale
plot(t, rms)
xlabel('Time (s)');
ylabel('RMS dB');

You missed a semicolon ; at the end of line [y,fs] = audioread(strcat(DirIn,'/',filelist(i).name)) . It signifies the end of a row and suppress an output of the code line. There is a nice blog-entry on this here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM