Loop through files with specific extension - matlab

I need to open many files in a loop, with the same extension.
Example file names are: c1_p1_t_r.mat,c1_p3_t_r.mat,c1_p6_t_r.mat,c1_p7_t_r.mat,c1_p10_t_r.mat,etc.
So basically, the first and last part of the file names are the same, but something in the middle changes.
I tried with:
Ext = 'c1_*t_r*.mat';
files = dir(Ext);
but it doesn't work. Any suggestion would be greatly appreciated.

Looking at the file names you shared you should use c1*t_r.mat rather than c1*t_r*.mat

Use files = dir('*.Ext'); You need the apostrophes to pass it as a string and the asterisk as the wildcard for file names. I think passing multiple asterisks here is the problem. You might resort to creating the variable name as a full string in case they are as similar though:
for ii = 1:NumberOfFiles
filename = sprintf('c1_p%dt_r.mat',ii);
%//load file with created name
end

Related

How to list down mat files with a specific prefix name?

I have a folder of images saved as .mat files files with the following names:
image-001-001.mat,image-001-002.mat,......., image-001-102.mat, image-002-001.mat,image-002-002.mat, ....,image-002-090.mat, etc.
I want to group the file names for each prefix. For example, list down all files that starts with image-001- prefix and list all images with image-002- and etc. for all files in the folder. I need the images of each group separately and do some processing on them.
Could someone please give some hints how can I do it?
Thanks in advance
See the documentation for dir, specifically the mention of wildcards.
You can get a list of .mat files which start with image-001 using
files_001 = dir('C:\myfolder\image-001*.mat');
% or if it's in the current directory then simply
% files_001 = dir('image-001*.mat');
To loop over several prefixes, you could use
prefixes = {'image-001', 'image-002', 'image-003'};
files = cell(numel(prefixes), 1);
for p = 1:numel(prefixes)
files{p} = dir([prefixes{p}, '*.mat']);
end
Aside:
If your prefixes really are that similar / ordered, there are many ways (e.g. using strcat) to quickly make the prefixes cell array.
YOu can pick all the images with start with image-001-xxx.mat as below:
files1 = dir('image-001*') ;

read multiple file from folder

I want to read multiple files from a folder but this code does not work properly:
direction=dir('data');
for i=3:length(direction)
Fold_name=strcat('data\',direction(i).name);
filename = fullfile(Fold_name);
fileid= fopen(filename);
data = fread (fileid)';
end
I modified your algorithm to make it easier
Just use this form :
folder='address\datafolder\' ( provide your folder address where data is located)
then:
filenames=dir([folder,'*.txt']); ( whatever your data format is, you can specify it in case you have other files you do not want to import, in this example, i used .txt format files)
for k = 1 : numel(filenames)
Do your code
end
It should work. It's a much more efficient method, as it can apply to any folder without you worrying about names, number order etc... Unless you want to specify certain files with the same format within the folder. I would recommend you to use a separate folder to put your files in.
In case of getting access to all the files after reading:
direction=dir('data');
for i=3:length(direction)
Fold_name=strcat('data\',direction(i).name);
filename = fullfile(Fold_name);
fileid(i)= fopen(filename);
data{i-2} = fread (fileid(i))';
end

How can I get a part of partfile?

This is probably a very simple question, but I am not able to find a straightforward solution.
[pathstr,name,ext] = fileparts('/xaaa/Data/Q2/CONUS/2002/PRECIPRATE.20020401.000000.tif')
Obviously, fileparts gives /xaaa/Data/Q2/CONUS/2002/
But I only want to access /xaaa/Data/Q2/CONUS/ and disregard the last section.
One way to do it is simply count the letters parthstr(1:20). But there must be an elegant alternative.
The most robust way to get a parent folder is to use '..' to access the folder above a provided folder. This is because it is independent of whether you specify an absolute or relative path as the input.
parent = fullfile(folder, '..');
In your case, since you have a filename and you want to get the parent, you can add a 'fileparts' call to that to get the direct parent folder, then pass it to the above.
parent = fullfile(fileparts(filename), '..');
This is more robust because it allows you to specify a relative file path such as 2002/PRECIPRATE.20020401.000000.tif which could fail if you tried to call fileparts multiple times.
If you only have a filename (with no directories because you're in the folder where the file is), you can use which to get an absolute path to the file.
parent = fullfile(fileparts(which(filename)), '..');
One simple way is to repeat the use of fileparts():
>> [pathstr,name,ext] = fileparts('/xaaa/Data/Q2/CONUS/2002/PRECIPRATE.20020401.000000.tif');
>> [parent_pathstr, name, ~] = fileparts(pathstr)
parent_pathstr =
/xaaa/Data/Q2/CONUS
name =
2002
Note: using the tilde ~ just ignores the file extension for the second call to fileparts() because you don't expect an extension.
There are three answers proposed already, but I do believe there's a better solution. I would match .*(?=/.*/) pattern using regexp, like this:
>> originalPath = '/xaaa/Data/Q2/CONUS/2002/PRECIPRATE.20020401.000000.tif';
>> res = char(regexp(originalPath, '.*(?=/.*/)', 'match'))
res =
/xaaa/Data/Q2/CONUS
If you need to go n levels deeper, just keep adding .*/ for each level, e.g.
>> res = char(regexp(originalPath, '.*(?=/.*/.*/)', 'match'))
res =
/xaaa/Data/Q2
For the OS-agnistic version, or if your path contains some mixture of back-slashes and forward-slashes, you can use the following regex: '.*(?=[/\\].*[/\\])'. Once again, to go several levels deper, just add an extra .*[/\\] for each level.
The benefit over using strsplit and fileparts is that you don't need to iterate anything - you get the answer with one simple regex.
Regarding .. - I myself used this solution for a long time for generating Matlab Path dynamically. However Matlab is sometimes not able to handle breakpoints correctly in the files that have .. in their path. To be exact, if you place a breakpoint in such a file, Matlab would ignore it unless there's another breakpoint that is triggered first (which is not in a file with .. in path).
It obviously handles relative paths as well.

Octave: create .csv files with varying file names stored in a sub folder

I have multiple arrays with string data. All of them should be exported into a .csv file. The file should be saved in a subfolder. The file name is variable.
I used the code as follows:
fpath = ('./Subfolder/');
m_date = inputdlg('Date of measurement [yyyymmdd_exp]');
m_name = inputdlg('Characteristic name of the expteriment');
fformat = ('.csv');
fullstring = strcat(fpath, m_date,'_', m_name, fformat);
dlmwrite(fullstring,measurement);
However, I get an error that FILE must be a filename string or numeric FID
What's the reason?
Best
Andreas
What you are asking to do is fairly straightforward for Matlab or Octave. The first part is creating a file with a filename that changes. the best way to do this is by concatenating the strings to build the one you want.
You can use: fullstring = strcat('string1','string2')
Or specifically: filenameandpath = strcat('./Subfolder/FixedFileName_',fname)
note that because strings are pretty much just character arrays, you can also just use:
fullstring = ['string1','string2']
now, if you want to create CSV data, you'll first have to read in the file, possibly parse the data in some way, then save it. As Andy mentioned above you may just be able to use dlmwrite to create the output file. We'll need to see a sample of the string data to have an idea whether any more work would need to be done before dlmwrite could handle it.

Name of files in a specific directory using matlab

I want to find the name of files in a specific directory. I know that the dir command return the name of files but it contains the file name with the their extension. Therefore, I used strfind to remove the extension of files as follows:
a = dir(fullfile(dataset_path, [dataset_category '\qrel']))
for i= 3: length(a)
name{i} = a(i).name(1:strfind(a(i).name, '.')-1)
I want a better approach without loop. I wonder is it a way to use vectorization for this purpose. I used the following code but it return an error
a = dir(fullfile(dataset_path, [dataset_category '\qrel']))
name = a.name(1:strfind(a.name, '.')-1)
You can do that with regular expressions:
name = regexprep({a.name}, '\.[^\.]*$', '');
This collects all names in a cell array ({a.name}). For each string it matches a dot (\.) followed by zero or more characters other than a dot ([^\.]*) at the end of the string ($), and removes that. Thanks to #Shai for the "other than a dot" correction, which makes sure that only the final dot is matched.