A loop-less solution:

d=dir;
d=d(~ismember({d.name},{'.','..'}));
Answer from Trisoloriansunscreen on Stack Overflow
Discussions

pick files within dir
I have a list create by dir i want to pick specific files in the dir the name differentiators are genreal name with "post" on the title and without I want to pick "post" files to create new tab... More on mathworks.com
🌐 mathworks.com
1
0
September 14, 2022
Trouble calling files using dir command
Trouble calling files using dir command. Learn more about dir, folder, file, .png, calling folder, image processing MATLAB More on mathworks.com
🌐 mathworks.com
2
0
November 7, 2018
Question about dir() function in matlab
dir does not take regular expressions or patterns (it only supports the * wildcard expression), but you can grab a list of all of the files, and then use MATLAB's pattern function to quickly find the ones you want. More on reddit.com
🌐 r/matlab
2
2
June 28, 2022
how to use command "dir"
Hi guys, When using command "dir", there always includes '.', '..'. Is there a way to eliminate these two items when using command "dir"(not postprocess)? Thanks, Zhong More on mathworks.com
🌐 mathworks.com
2
0
November 23, 2011
Top answer
1 of 11
58

A loop-less solution:

d=dir;
d=d(~ismember({d.name},{'.','..'}));
2 of 11
16

TL; DR

Scroll to the bottom of my answer for a function that lists directory contents except . and ...

Detailed answer

The . and .. entries correspond to the current folder and the parent folder, respectively. In *nix shells, you can use commands like ls -lA to list everything but . and ... Sadly, MATLAB's dir doesn't offer this functionality.

However, all is not lost. The elements of the output struct array returned by the dir function are actually ordered in lexicographical order based on the name field. This means that, if your current MATLAB folder contains files/folders that start by any character of ASCII code point smaller than that of the full stop (46, in decimal), then . and .. willl not correspond to the first two elements of that struct array.

Here is an illustrative example: if your current MATLAB folder has the following structure (!hello and 'world being either files or folders),

.
├── !hello
└── 'world

then you get this

>> f = dir;
>> for k = 1 : length(f), disp(f(k).name), end
!hello
'world
.
..

Why are . and .. not the first two entries, here? Because both the exclamation point and the single quote have smaller code points (33 and 39, in decimal, resp.) than that of the full stop (46, in decimal).

I refer you to this ASCII table for an exhaustive list of the visible characters that have an ASCII code point smaller than that of the full stop; note that not all of them are necessarily legal filename characters, though.

A custom dir function that does not list . and ..

Right after invoking dir, you can always get rid of the two offending entries from the struct array before manipulating it. Moreover, for convenience, if you want to save yourself some mental overhead, you can always write a custom dir function that does what you want:

function listing = dir2(varargin)

if nargin == 0
    name = '.';
elseif nargin == 1
    name = varargin{1};
else
    error('Too many input arguments.')
end

listing = dir(name);

inds = [];
n    = 0;
k    = 1;

while n < 2 && k <= length(listing)
    if any(strcmp(listing(k).name, {'.', '..'}))
        inds(end + 1) = k;
        n = n + 1;
    end
    k = k + 1;
end

listing(inds) = [];

Test

Assuming the same directory structure as before, you get the following:

>> f = dir2;
>> for k = 1 : length(f), disp(f(k).name), end
!hello
'world
🌐
MathWorks
mathworks.com › matlabcentral › answers › 1805380-pick-files-within-dir
pick files within dir - MATLAB Answers - MATLAB Central
September 14, 2022 - It is common but mistaken to believe that the . and .. entries will always be the first two entries returned by dir(), so it is not unusual for people to take dir() results and loop starting with entry #3. That is incorrect code in every operating system that MATLAB has ever been supported on.
🌐
MathWorks
mathworks.com › matlabcentral › answers › 428508-trouble-calling-files-using-dir-command
Trouble calling files using dir command - MATLAB Answers - MATLAB Central
November 7, 2018 - The dir() function expects a character array as input and a struct containing information of the files in that directory (or an empty struct if it is not a correct file path). Your error comes from the fact that DBImages is not declared yet ...
🌐
Reddit
reddit.com › r/matlab › question about dir() function in matlab
r/matlab on Reddit: Question about dir() function in matlab
June 28, 2022 -

can you specify a range using dir() function? example: listing = dir('./data_*'); % This would just list all the data in that directory

Instead of listing all the # of files in that directory, I want to set a range and exclude all the data before and after. each data file has a specified number data_0000, data_0005, data_0010, etc. I trid using https://es.mathworks.com/help/matlab/ref/dir.html but didn't get much help from there.

Essentially I only want to consider the data in the range from 180 to 360.

Data_0180 to data_0360.

Within that range I'd have all the data for 180, 185, 190, ... 360.

🌐
MathWorks
mathworks.com › matlab › data import and analysis › data import and export › web access and streaming › ftp file operations
dir - List folder contents on SFTP or FTP server - MATLAB
List details of the contents on an SFTP server. The dir function can return a structure array that contains the name, modification date, and size of each item in the specified folder.
Find elsewhere
🌐
MathWorks
mathworks.com › matlabcentral › answers › 22110-how-to-use-command-dir
how to use command "dir" - MATLAB Answers - MATLAB Central
November 23, 2011 - For example, dir('*.mat') instead of dir('*') and assuming that everything you get back will be a .mat file.
Top answer
1 of 8
129

Update: Given that this post is quite old, and I've modified this utility a lot for my own use during that time, I thought I should post a new version. My newest code can be found on The MathWorks File Exchange: dirPlus.m. You can also get the source from GitHub.

I made a number of improvements. It now gives you options to prepend the full path or return just the file name (incorporated from Doresoom and Oz Radiano) and apply a regular expression pattern to the file names (incorporated from Peter D). In addition, I added the ability to apply a validation function to each file, allowing you to select them based on criteria other than just their names (i.e. file size, content, creation date, etc.).


NOTE: In newer versions of MATLAB (R2016b and later), the dir function has recursive search capabilities! So you can do this to get a list of all *.m files in all subfolders of the current folder:

dirData = dir('**/*.m');

Old code: (for posterity)

Here's a function that searches recursively through all subdirectories of a given directory, collecting a list of all file names it finds:

function fileList = getAllFiles(dirName)

  dirData = dir(dirName);      %# Get the data for the current directory
  dirIndex = [dirData.isdir];  %# Find the index for directories
  fileList = {dirData(~dirIndex).name}';  %'# Get a list of the files
  if ~isempty(fileList)
    fileList = cellfun(@(x) fullfile(dirName,x),...  %# Prepend path to files
                       fileList,'UniformOutput',false);
  end
  subDirs = {dirData(dirIndex).name};  %# Get a list of the subdirectories
  validIndex = ~ismember(subDirs,{'.','..'});  %# Find index of subdirectories
                                               %#   that are not '.' or '..'
  for iDir = find(validIndex)                  %# Loop over valid subdirectories
    nextDir = fullfile(dirName,subDirs{iDir});    %# Get the subdirectory path
    fileList = [fileList; getAllFiles(nextDir)];  %# Recursively call getAllFiles
  end

end

After saving the above function somewhere on your MATLAB path, you can call it in the following way:

fileList = getAllFiles('D:\dic');
2 of 8
25

You're looking for dir to return the directory contents.

To loop over the results, you can simply do the following:

dirlist = dir('.');
for i = 1:length(dirlist)
    dirlist(i)
end

This should give you output in the following format, e.g.:

name: 'my_file'
date: '01-Jan-2010 12:00:00'
bytes: 56
isdir: 0
datenum: []
🌐
MathWorks
mathworks.com › matlabcentral › answers › 2074826-a-question-about-list-folder-contents-with-dir
A question about list folder contents with dir - MATLAB Answers - MATLAB Central
January 26, 2024 - For example, if your directory is C:\Users\Bob, . refers to C:\Users\Bob and .. refers to C:\Users. ... https://www.mathworks.com/matlabcentral/answers/2074826-a-question-about-list-folder-contents-with-dir#comment_3043216
🌐
MathWorks
mathworks.com › matlabcentral › answers › 1791125-getting-a-list-of-files-should-be-easy-but
Getting a List of Files.... Should Be Easy But - MATLAB Answers - MATLAB Central
August 30, 2022 - In most typical cases, people using Matlab dir feature may be looking for a specific range of files such as *.txt or *.jpg, or be exploring directories which do not contain unusual, hidden or system files or directories.
🌐
Duke University
people.duke.edu › ~jmp33 › matlab › working_with_directories.html
Working With Directories
This is a special matlab string that changes based on operating system. On Unix and Mac, it gives '/', while on Windows, it returns '\'. This gets us around the code above, where I had to tell you to replace your slash with a backslash to make it work in Windows. ... matfiles=dir('*.mat'); %get a listing of all the .mat files; matnames={matfiles.name}; wholename=[pwd filesep matnames{1}] %concatenate current directory name and filename into a single string
🌐
MathWorks
mathworks.com › matlab › programming › files and folders › file operations
ls - List folder contents - MATLAB
Use the dir command to return file attributes for each file and folder in the output argument. You can also view files and folders in the Files panel by issuing the filebrowser command. ... Run the command by entering it in the MATLAB Command Window.
🌐
Upc
www-eio.upc.es › lceio › manuals › matlab › TECHDOC › REF › DIR.HTML
dir
Use pathnames, wildcards, and any options available in your operating system. names = dir('dirname') or names = dir returns the results in an m-by-1 structure with the fields: Examples · cd /Matlab/Toolbox/Local; dir Contents.m matlabrc.m siteid.m userpath.m names = dir names = 4x1 struct array with fields: name date bytes isdir ·