Reading all the files in sequence in MATLAB - matlab

I am trying to read all the images in the folder in MATLAB using this code
flst=dir(str_Expfold);
But it shows me output like this. which is not the sequence as i want.
Can anyone please tell me how can i read all of them in sequence?
for giving downmark, please explain the reason for that too.

By alphabetical order depth10 comes before depth2. If at all possible, when creating string + num type filenames, use a fixed width numerical part (e.g. depth01, depth02) - this tends to avoid sorting problems.
If you are stuck with the filenames you have, and know the filename pattern, though, you can not bother using dir at all and create your filename list in the correct order in the first place:
for n = 1:50
fname = sprintf('depth%d.png',n);
% code to read and process images goes here
end

From the Matlab forums, the dir command output sorting is not specified, but it seems to be purely alphabetical order (with purely I mean that it does not take into account sorter filenames first). Therefore, you would have to manually sort the names. The following code is taken from this link (you probably want to change the file extension):
list = dir(fullfile(cd, '*.mat'));
name = {list.name};
str = sprintf('%s#', name{:});
num = sscanf(str, 'r_%d.mat#');
[dummy, index] = sort(num);
name = name(index);

Related

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.

Matlab : Counting image in a folder using matlab GUI

I want to count the number of image in a folder using a GUI created in Matlab guide 2015b.
I have written this code:
Id = 3 (actually the value of id will be given by user at run time)
path =strcat ( ' c:\user\Desktop\New\TrainData\',Id)
path=strcat (path,'\')
d=dir (path)
n=length (d)
It shows the error that dir can not be used for cell input. This code is working when I use command prompt.
It shows error only when I want to use it through GUI. Initially I thought that it's a problem regarding the path.
So I displayed the path but it gave the perfect result.
I am confused. Kindly provide some solutions in Matlab
Instead of strcat you should use fullfile:
path = fullfile('c:\user\Desktop\New\TrainData',num2str(Id))
And be careful with dir, dir also list the subfolder so check that you only take into account the image file:
d = dir(path);
name = d(~[d.isdir]).name
Chances are you're getting your Id variable from a inputdlg or something. It is being read in as a cell array of strings rather than a string. You can check this using iscell:
iscell(Id)
% 1
You don't see any issues until you hit the dir command because strcat is able to handle this just fine but also yields a cell array of strings.
out = strcat('123', {'4'});
class(out)
% cell
If you read your error message thoroughly, the error explicitly states that the input to dir is a cell and not a string. The way to fix this is to first check if Id is a cell array and convert to a string if necessary.
Id = inputdlg('Enter an ID');
% Convert to a string if Id is a cell array
if iscell(Id)
Id = Id{1};
end
% Get a listing of all files/directories
d = dir(fullfile(folder, num2str(I)));
% Get number of files
nFiles = sum(~[d.isdir]);
Also, you don't want to try to concatenate a number with a string (strcat('abc', 1)) because this will convert the number to it's ASCII code. Instead you'll want to use num2str as shown above.

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.

looping and ordering extracted data in MatLab

I have hundreds of data files, named file001~file400 for example, and should pick a numeric value from each. I know how to pick each number, but, since there are too many files, I need to loop the command and order all extracted numbers with regard to the number of corresponding file. I appreciate any help.
The problem is to loop over all files. This can be done in the following way:
for i = 1:400
filename = sprintf('file%03d',i);
// do the number picking, etc. using the filename.
end
EDIT: Per request, for filenames FT00100 to FT05320, we we make two small changes, one in the loop range and one in the first parameter to sprintf:
for i = 100:5320
filename = sprintf('FT%05d',i);
// do the number picking, etc. using the filename.
end

Loading MATLAB .mat files in alphanumerical order

I'm currently attempting to load a number of MATLAB files which all contain the same variable in order to make a matrix of all the values.
These files all start with a number (i.e. 40_analysed.mat), which was previously extracted from different raw data files using regular expressions, meaning I have a vector composed of all the individual numbers (id).
When I try to load the values and display the data for all individuals in a single matrix using the code below, the files aren't loaded alphanumerically (i.e. according to id), instead appearing to be loaded randomly.
file = dir('*_analysed.mat');
for i=1:length(id);
load(file(i).name,'means');
overallThresholds{i} = means;
end
overallMeans = cell2mat(overallThresholds)
How could I do this so the resulting matrix would be in the correct order? Apologies if this question doesn't make much sense, the problem is a little hard to articulate!
If your filenames don't have a fixed-precision number (as #FakeDIY points out, that would mean they would already be sorted), you could do something like this:
file = dir('*_analysed.mat');
overalThresholds = cell(1, length(id));
IDs = zeros(1, length(id));
for i = 1:length(id)
fileName = file(i).name;
IDs(i) = str2double( strrep( fileName, '_analysed.mat', '' ) );
data = load(fileName, 'means');
overallThresholds{i} = data.means;
end
[~, reordering] = sort(IDs);
overallThresholds = overallThresholds(reordering);
In other words, store the file ID in a separate array as you're going along, and then reorder overallThresholds to be in sorted order of IDs using the second output of SORT.
(I also pre-allocated the arrays, and use the functional form of LOAD, but you don't really need to do that).
When one uses dir command, it is not promised that the results will be in alphabetical order. In fact, the manual says explicitly that:
dir lists the files and folders in the MATLAB current folder. Results
appear in the order returned by the operating system.
Even if you did get this in alphabetical order, nothing assures you that you will get it next time. Thus, you must order the results from dir using sort command.
[~,order] = sort( {file.name} );
file = file(order);