How to skip every second file in directory for for loop

2 ビュー (過去 30 日間)
Louise Wilson
Louise Wilson 2020 年 4 月 27 日
コメント済み: Louise Wilson 2022 年 8 月 24 日
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 件のコメント
Stephen23
Stephen23 2020 年 4 月 28 日
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 2020 年 4 月 28 日
Thanks Stephen! Updated to answer re:Image Analyst, all good!

サインインしてコメントする。

回答 (1 件)

Louise Wilson
Louise Wilson 2020 年 4 月 28 日
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
  3 件のコメント
Benjamin Colbert
Benjamin Colbert 2022 年 8 月 24 日
To modify this to skip 23 files (e.g., read one file per day), would you simply change for i=1:2:length(directory) to for i=1:24:length(directory)
Louise Wilson
Louise Wilson 2022 年 8 月 24 日
Yes, that will select every 24th item of i. Run the first couple of iterations and check it's selecting what you think it is/want it to. It will only work to select one file per day if you have 24 files per day.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeSearch Path についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by