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

1 view (last 30 days)
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.

Accepted Answer

KSSV
KSSV on 11 Jan 2017
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 Comments
Oliver Bunn
Oliver Bunn on 11 Jan 2017
I have tried this but this only tells me the position of Pressure.mat rather then outputting the entire file name
KSSV
KSSV on 11 Jan 2017
Edited: KSSV on 11 Jan 2017
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

Sign in to comment.

More Answers (1)

Stephen23
Stephen23 on 11 Jan 2017
Edited: Stephen23 on 11 Jan 2017
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.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!