Want to define a cell vector according to the files in a directory

1 view (last 30 days)
I want to define a variable (say "files") as a cell array containing the names of the folders in a specific directory. Consider the directory of interest (home/directory) that contains 4 folders named 'AAAA' 'BBB' 'CC' 'D'. The following command yields the following result:
files=ls('/home/directory');
files=AAAABBBCCD
I want files to be a cell array containing 4 elements
files(1) = AAAA
files(2) = BBB
files(3) = CC
files(4) = D
Any ideas? Thanks

Accepted Answer

Walter Roberson
Walter Roberson on 26 Jan 2018
dinfo = dir('/home/directory');
files = {dinfo.name};
Note that the directory will not be included as part of what is stored in files
Do not use ls() for this purpose: On OS-X and Linux it invokes the shell ls command, which produces multiple columns per line, space separated, with embedded newline characters. You might be tempted to use that and then to split at whitespace, but if you do that then you will accidentally file names that contain whitespace in them. The dir() that I show will not have problems this way.

More Answers (0)

Categories

Find more on File Operations in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!