Trouble calling files using dir command
63 views (last 30 days)
ImageFiles = dir(DBImages);
%%%extracts information of all files whose filename end with `.png?.
^^ This line of code was given to me by my professor and seems to have worked for everyone else, but I can't get it to call the images in my DBImages folder. When I try to run the script, I get this error:
Undefined function or variable 'DBImages'.
I'm not really sure why my DBImages file can't be found; I selected it and clicked on "add folder and subfolders to path," which I figured would make it accessible, but I'm still receiving the asme error. There are no spelling mistake here either. I'm not sure, but I don't think I should need any special toolboxes or anything, as DBImages is just a folder with a few .m files and a lot of .png files. Any thoughts?
jonas on 7 Nov 2018
Edited: jonas on 7 Nov 2018
I'm not surprised it does not work. The variable DBImages should probably be assigned a string at some point prior to calling dir. Just learn how the function dir works instead:
files = dir('folderpath\*.png')
files = dir('C:\MyImages\*.png')
if DBImages is the folder name, then you probably just failed to make it a string
files = dir('DBImages')
Although the above is possible, I recommend adding the entire folder path, with the only downside being that you have to alter the script if you move the folder.
More Answers (1)
Nick on 7 Nov 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 when you call the function and without quotation marks MATLAB thinks you are referring to a variable or a function when using text.
So the short answer would be you need to use quotation marks:
ImageFiles = dir('DBImages');
This however assumes you are in the parent directory of a folder called DBImages. And the structure will contain all possible files inside this folder.
Another approach is using a full file path and adding the extension like this
ImageFiles = dir(fullfile('YourFilePath','*.png'));
With YourFilePath being the full file path to the directory containing the PNG images. The '*.png' will filter out everything that does not end with .png. The output struct will contain folder, name, ...etc. for each file. You can then use use it like this:
% short example how to use the struct - prints file names in that
% folder to command window
for ii = 1:numel(ImageFiles)