MATLAB Answers

How to skip every second file in directory for for loop

2 views (last 30 days)
Louise Wilson
Louise Wilson on 27 Apr 2020
Commented: Stephen Cobeldick on 28 Apr 2020
I have a folder of .wav files which I am cutting to a shorter length and then re-writing. I would like to do this for every second file in the directory.
How can I adapt my code to do this?
direcName = 'H:\SoundTrap\wav\New folder\*.wav'; %folder
directory = dir(direcName); %all files in folder
[pathstr,name,ext] = fileparts(direcName);
for i=1:length(directory)
usefile = directory(i).name;
fileName = strcat(pathstr,'\',usefile);
[y, Fs] = audioread(fileName,[1 2]);
startpos = 4 * Fs; %start position in seconds
endpos = 119 * Fs; %end position in seconds
% Store edited version
[ynew, Fs] = audioread(fileName, [startpos endpos]); %read in section of file
% Write new file
[pathstr,name,ext] = fileparts(fileName);
folder='H:\SoundTrap\wav\New folder\Cut files';
outFileName = strcat(folder, '\', name, '.cut',ext);
audiowrite(outFileName, ynew, Fs);
end

  3 Comments

Stephen Cobeldick
Stephen Cobeldick on 28 Apr 2020
You can improve the code by using fullfile rather than concatenating strings, e.g. replace this:
fileName = strcat(pathstr,'\',usefile);
with
fileName = fullfile(pathstr,usefile);
Louise Wilson
Louise Wilson on 28 Apr 2020
Thanks Stephen! Updated to answer re:Image Analyst, all good!

Sign in to comment.

Answers (1)

Louise Wilson
Louise Wilson on 28 Apr 2020
The answer is...
direcName = 'H:\SoundTrap\wav\New folder\*.wav'; %folder
directory = dir(direcName); %all files in folder
[pathstr,name,ext] = fileparts(direcName);
for i=1:2:length(directory)
usefile = directory(i).name;
fileName = fullfile(pathstr, usefile);
[y, Fs] = audioread(fileName,[1 2]);
startpos = 4 * Fs; %start position in seconds
endpos = 119 * Fs; %end position in seconds
% Store edited version
[ynew, Fs] = audioread(fileName, [startpos endpos]); %read in section of file
% Write new file
[pathstr,name,ext] = fileparts(fileName);
folder='H:\SoundTrap\wav\New folder\Cut files';
outFileName = strcat(folder, '\', name, '.cut',ext);
audiowrite(outFileName, ynew, Fs);
end

  1 Comment

Stephen Cobeldick
Stephen Cobeldick on 28 Apr 2020
  • replace string concatenation with fullfile and sprintf.
  • avoid the first fileparts by providing just the directory path.
  • unused output arguments replaced with tilde ~
D = 'H:\SoundTrap\wav\New folder';
S = dir(fullfile(D,'*.wav'));
for k = 1:2:numel(S)
F = fullfile(D,S(k).name);
[~,Fs] = audioread(F,[1,2]);
% read in section of file:
[y,Fs] = audioread(F,Fs.*[4,119]);
% Write new file
[~,N,E] = fileparts(S(k).name);
F = fullfile(D,'Cut files',sprintf('%s.cut%s',N,E));
audiowrite(F,y,Fs);
end

Sign in to comment.

Products


Release

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!