Search code examples
matlabdir

List of specific files in a directory using `dir` command in matlab


This questions is regarding dir command in matlab.

PREAMBLE

I have a set of files: 01.dat, 02.dat, 03.dat, ..., 20.dat. When I type in command line: dir('*.dat'), I will see all my files. If I want to pick only particular files in the range [01-09], I will type dir('0*.dat').

QUESTION

Suppose, I need to pick only those files, which are in the specific range, namely: 03.dat, 04.dat, 05.dat, 06.dat. How can I do it with dir?

I need something like dir('0[3:6].dat'). I want to avoid using a=dir('*.dat'); a(3:6).name; due to some reasons related to the data set. So, I want to specify the desired range at the level of "dir" command only. Any suggestions? Many thanks in advance!!


Solution

  • The function dir could be associated with arrayfun: it will apply a dir command to each member of a vector, for instance 3:6. Here, filenames will refer to four files from 03.dat to 06.dat.

    Pseudo-code dir('0[3:6].dat') could be translated by:

    filenames = arrayfun(@(x) dir(['0' num2str(x) '.dat']), 3:6);