How can I read in specific cells which contain file names ending in 'Pressure.mat'?

1 回表示 (過去 30 日間)
Oliver Bunn
Oliver Bunn 2017 年 1 月 11 日
コメント済み: Stephen23 2017 年 1 月 11 日
I have a list of 490 files in a matrix, I want to only read the files which end in 'Pressure.mat', if it does not end in this I don't want to read it. What function can I use to do this? Even creating a new matrix which only contains these specific cells containing the files would be what I need.

採用された回答

KSSV
KSSV 2017 年 1 月 11 日
You can run a loop, and use strfind. Find for Pressure.mat in the string, if the output is not empty, then you have to read the file.
  2 件のコメント
Oliver Bunn
Oliver Bunn 2017 年 1 月 11 日
I have tried this but this only tells me the position of Pressure.mat rather then outputting the entire file name
KSSV
KSSV 2017 年 1 月 11 日
編集済み: KSSV 2017 年 1 月 11 日
You have filename already in hand in matrix...If it is giving indices of position then you have to pick that matrix(i,j) filename. Else not.
M = [{'coolpressure.mat'} {'cool.mat'} ; {'hello.mat'} {'hipressure.mat'}] ;
for i = 1:2
for j = 1:2
idx = strfind(M{i,j},'pressure.mat') ;
if ~isempty(idx)
fprintf('pick the %s file \n',M{i,j})
end
end
end

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

その他の回答 (1 件)

Stephen23
Stephen23 2017 年 1 月 11 日
編集済み: Stephen23 2017 年 1 月 11 日
Do not use ugly loops to do this. MATLAB is much more beautiful than that!
Do not use strfind to do this: it will match that string anywhere in the filename, e.g. it will match 'Pressure.mat.txt' or 'Pressure.mat-old', even though these are not what you are looking for.
A much more robust solution is to use regexp to match exactly the string you want:
>> C = {...
'NotThisFile.mat';...
'ThisPressure.mat';...
'YesPressure.mat';...
'NoPressure.mat.txt';...
'WrongPressure.txt';...
};
>> idx = cellfun('isempty',regexp(C,'Pressure\.mat$')); % $ matches end of string!
>> D = C(~idx)
D =
'ThisPressure.mat'
'YesPressure.mat'
You can easily loop over these names:
>> for k = find(~idx)', C{k}, end
ans =
ThisPressure.mat
ans =
YesPressure.mat
Note that regexp is case sensitive. You can use regexpi for a case insensitive match.
  2 件のコメント
Oliver Bunn
Oliver Bunn 2017 年 1 月 11 日
Works Perfectly! Thank you
Stephen23
Stephen23 2017 年 1 月 11 日
@Oliver Bunn: you can vote for my answer if it works for you.

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

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by