MATLAB Answers


list names in an array

Asked by Barakat Ibrhim on 13 Jun 2019
Latest activity Commented on by Adam Danz
on 14 Jun 2019
I have many files that i want to list their names in an array but the name is full for example


It sounds like you're doing something wrong.
Does your code look like this?
d = dir('C:\Users\name\Documents\MATLAB\');
% list all file
It would be handy if dir took an argument, allowing specification of the full path in the output. It seems like this would be a common enough thing to want to do.
Agreed. I suggested testing because the OP stated that it was only returning file name when it should be returning the file extension as well.

Sign in to comment.

2 Answers

Answer by Guillaume
on 13 Jun 2019

A lot simpler than all that has been suggested:
foldercontent = dir('C:\somewhere\*.csv');
filelist = fullfile({foldercontent.folder}, {}); %that's all that is needed.
As said, if a string array is needed, string will convert the cell array of char vectors into a string array


Show 1 older comment
I would argue that clarity completely trumps speed in this case particularly as the speed difference would be insignificant compared to the file IO that will inevitably follow.
+1 fullfile is definitely the way to go.
It is highly unlikely that constructing filenames is going to be a bottleneck in the code.
Definitely clairity over milliseconds.

Sign in to comment.

Answer by the cyclist
on 13 Jun 2019

I'm pretty sure there is a better, simpler way to do this, but I believe this does what you want:
s = dir;
fileList = cellfun(@(x,y)[x,'/',y],{s.folder}',{}','UniformOutput',false);


Show 1 older comment
will convert the cell array to a string array (at least in R2018b).
"I'm pretty sure there is a better, simpler way..."
s = dir;
fileList = strcat({s.folder}',repmat({'/'},size(s)),{}');
"I'm pretty sure there is a better, simpler way..."
S = dir(...);
F = cellfun(@fullfile,{S.folder}',{}','uni',0);
Or simply:
F = fullfile({S.folder},{});

Sign in to comment.