How to exclude files from a loop

12 ビュー (過去 30 日間)
Sophie Williams
Sophie Williams 2017 年 12 月 29 日
コメント済み: Image Analyst 2021 年 10 月 26 日
I have 70 files looped in to my script and I need to exclude some of the files (9 15 21 30 35 60) as these were false trials in there a code to do this?
  1 件のコメント
Jan
Jan 2017 年 12 月 29 日
@Sophie: "I have 70 files looped in to my script" - while this is surely clear to you, because you see the code in front of you, the readers have to guess, what this means. How can a "file" be "looped"? Post your code to allow to suggest a modification of it.

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

回答 (2 件)

ANKUR KUMAR
ANKUR KUMAR 2017 年 12 月 29 日
編集済み: ANKUR KUMAR 2017 年 12 月 30 日
If you are using F=dir('*.nc') (.nc is the file extension or it can be any file extension) to read all 70 files, then you can simply use
F([9,15,21,30,35,60])=[]
  2 件のコメント
Jan
Jan 2017 年 12 月 29 日
No. F(9,15,21,30,35,60) would access a 6 dimensional array. Maybe you mean:
F([9,15,21,30,35,60]) = [];
ANKUR KUMAR
ANKUR KUMAR 2017 年 12 月 30 日
Ops. Sorry.. Typing error.

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


Image Analyst
Image Analyst 2017 年 12 月 30 日
What do you have about them? Their filename? If so, you can just ismember() to see if the current filename is one of the ones to be excluded, then continue. Something like (untested)
dirList = dir('*.png');
for k = 1 : numberOfFiles
thisFilename = fullfile(dirList(k).folder, dirList.filename);
if any(ismember(thisFilename, filesToBeSkipped))
continue; % Skip this one
end
% Continue with code for files you want to process.
end
  2 件のコメント
CheshireM
CheshireM 2021 年 10 月 26 日
@Image Analyst if I use your suggestion, for some reason nothing happens ('time.xlsx' - file I dont want to read). Do you know the reason? How can I fix this type of error, when nothing is printing and I dont understand why?
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
if any(ismember(baseFileName, 'time.xlsx'))
continue; % Skip this one
end
fprintf(1, 'Now reading %s\n', fullFileName)
end
Image Analyst
Image Analyst 2021 年 10 月 26 日
Because you did not give a list. You gave a single string. To skip that one particular file, you can do
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
if strcmpi(baseFileName, 'time.xlsx')
continue; % Skip this one
end
fprintf(1, 'Now reading %s\n', fullFileName)
end

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

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by