List files in current directory based on a pattern in a variable.

Hello, I have a column vector weeklyDates = [20101031;20101107;etc...]. In my directory i have files containing these patterns within their file names (ex: L3m_20101024-20101031_sst.nc).
I want to loop over weeklyDates such that in each iteration i get all the files containing the pattern in weeklyDates at each row.
Is there a way to use the function dir so that it reads each pattern contained in the variable weeklyDates iteratively?
Desired result: dir('*20101031*.nc')
dir('*20101107*.nc') ...

 採用された回答

dpb
dpb 2022 年 7 月 5 日
編集済み: dpb 2022 年 7 月 5 日

0 投票

weeklyDates = [20101031;20101107;...];
for i=1:numel(weeklyDates)
pattern=sprintf('*%d*.nc',weeklyDates(i));
d=dir(pattern);
for j=1:numel(d)
fname=d(j).name;
% process each file here...
end
end
NB: Corrected typo in format string -- also, dir() doesn't like the cellstr() so reverted back to old sprintf()

6 件のコメント

Ziad Sari El Dine
Ziad Sari El Dine 2022 年 7 月 5 日
Thanks!
Ziad Sari El Dine
Ziad Sari El Dine 2022 年 7 月 5 日
It is giving an error: Error using compose (line 98)
Invalid format.
dpb
dpb 2022 年 7 月 5 日
Typo - there's a second '%' after the %d instead of the intended '*' wildcard...
fmt='*%d*.nc';
Ziad Sari El Dine
Ziad Sari El Dine 2022 年 7 月 5 日
Error using sscanf
First argument must be a string scalar or character vector.
I tried changing my array to a string array but it gave no result
dpb
dpb 2022 年 7 月 5 日
Before AM coffee!!! NOT sscanf here, it's sprintf, of course.
>> pattern=sprintf('*%d*.nc',20101031)
pattern =
'*20101031*.nc'
>>
Ziad Sari El Dine
Ziad Sari El Dine 2022 年 7 月 5 日
Haha thanks for the help. Much appreciated!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeSearch Path についてさらに検索

製品

リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by