MATLAB – How to check if a file or a folder exists

So you want to check if a file or a folder exists in MATLAB? Here’s how to do it.

% The file/folder to find.
fPath = 'aLittleFile.m';
 
% To see what each of these "magic numbers" mean, go to, 
% http://www.mathworks.com/help/techdoc/ref/exist.html
if isequal(exist(fPath,'file'),2) % 2 means it's a file.
    % We have a file!
    display('a file!');
elseif isequal(exist(fPath, 'dir'),7) % 7 = directory.
    % We have a folder!
    display('a folder');
else
    % We have an invalid file or folder.
    display('an error!');
end

Note that we use the isequal bit to check if it is actually a file or a folder. If we take the isequal check out, then the first if statement would be true for a file and a folder (since exist(fPath,’file’) would return 7, thus the if statement would be true)!

Questions/comments? If you just want to say thanks, consider sharing this article or following me on Twitter!