create a loop using regexp

1 回表示 (過去 30 日間)
Nicolas
Nicolas 2014 年 8 月 13 日
コメント済み: Nicolas 2014 年 8 月 13 日
I have imported a bench of text file into MATLAB using
list_files2load = dir(fullfile(directory1,'Mod1*));
In those files (here is an example: Mod1-A-00k.txt, Mod1-A-10k.txt, Mod1-A-30k.txt; Mod1-B-00k.txt, Mod1-B-10k.txt, Mod1-B-30k.txt), I would like to pick first only the ones that end with '*00k.txt', so I do :
a={'Mod1-A-00k.txt', 'Mod1-A-10k.txt', 'Mod1-A-30k.txt', 'Mod1-B-00k.txt', 'Mod1-B-10k.txt', 'Mod1-B-30k.txt'}
idx=~cellfun(@isempty,regexp(a,'.+(00k.txt)\>','match'))
b=a(idx)
Now I would like to know if it is possible with regexp to create a loop which first starts with piking the files ending with '*00k.txt' and in the second loop the files ending with '*10k.txt' and so on.
Thank you

採用された回答

Geoff Hayes
Geoff Hayes 2014 年 8 月 13 日
Nicolas - for sure you can add a loop as long as you know what to increment by at each iteration. If we assume an increment of 10 (given your pattern of 00,10,30) then we could wrap your above code in a for loop as
for u=0:10:50
% create the file pattern
filePattern = sprintf('%02d',u);
idx=~cellfun(@isempty,regexp(a,['.+(' filePattern 'k.txt)\>'],'match'));
% if any value in logical array is one then save to b
if any(idx)
b=a(idx)
end
end
Running the above code with your a produces the following output
b =
'Mod1-A-00k.txt' 'Mod1-B-00k.txt'
b =
'Mod1-A-10k.txt' 'Mod1-B-10k.txt'
b =
'Mod1-A-30k.txt' 'Mod1-B-30k.txt'
  1 件のコメント
Nicolas
Nicolas 2014 年 8 月 13 日
thank you, that's perfect.

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

その他の回答 (1 件)

Christopher Berry
Christopher Berry 2014 年 8 月 13 日
You can do this with regular expressions, but your name requirements seem simple enough to do with dir and sprintf instead.
My suggestion would be to put the dir call inside your for loop and try something like:
for i=0:10:30
str = sprintf('Mod1*%0dk.txt',i)
list_files2load = dir(fullfile(directory1,str));
%DO WORK ON FILES HERE
end
See the documenation for sprintf here:
  1 件のコメント
Nicolas
Nicolas 2014 年 8 月 13 日
thanks that's also really fitting what I need. thanks for the link too.

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

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by