0

I have a set of files in a folder that I want to convert to a different type using MATLAB, ie. for each file in this folder do "x".

I have seen answers that suggest the use of the "dir" function to create a structure that contains all the files as elements (Loop through files in a folder in matlab). However, this function requires me to specify the file type (.csv, .txt, etc). The files I want to process are from a very old microscope and have the file suffixes .000, .001, .002, etc so I'm unable to use the solutions suggested elsewhere.

Does anyone know how I can get around this problem? This is my first time using MATLAB so any help would be greatly appreciated. All the best!

Eli Rees
  • 178
  • 2
  • 14
  • 3
    "However, this function requires me to specify the file type". This is incorrect, just read the documentation, at the start. try `test=dir;` and inspect the values of `test` – Ander Biguri Aug 23 '22 at 14:36
  • 2
    [This example](https://www.mathworks.com/help/matlab/ref/dir.html#bup_80o-1) in the MATLAB documentation doesn't specify a file type, only a folder path. Have you tried that? – beaker Aug 23 '22 at 14:43
  • @beaker I was actually just looking at this page I think you're right. When I use dir some of the elements in this structure are the files I want now, but they don't seem to be in an order that relates to the order the files are in in the folder? – Eli Rees Aug 23 '22 at 14:50
  • 1
    files in a folder are not "in an order", they are just there. Then when you look at them with any software, they will be given some order, that often you can chose. So there is no such thing as "file order". Just order them as you wish. – Ander Biguri Aug 23 '22 at 15:04

1 Answers1

1

As suggested by beaker and Ander Biguri, you can do this by getting all files and then sorting.

Here is the related code with explanations inline:

baseDir = 'C:\mydir';

files = dir(baseDir);
files( [ files.isdir] ) = [];   % This removes directories, especially '.' and '..'.

fileNames = cell(size(files));  % In this cell, we store the file names.
fileExt   = cell(size(files));  % In this cell, we store the file extensions.
for k = 1 : numel(fileNames )
    cf = files(k);
    fileNames{k}      = [ cf.folder filesep cf.name];  % Get file name
    [~,~, fileExt{k}] = fileparts( cf.name );          % Get extension
end

[~,idx] = sort( fileExt );    % Get index to sort by extension
fileNames = fileNames( idx ); % Do the actual sorting
user16372530
  • 692
  • 2
  • 13