How to check if a file exists in Matlab?

if exist('JaccardDistance', 'file')==1 load('JaccardDistance'); else % Do things end 

The JaccardDistance file is located in the same folder where this code is executed. The problem is that the else part is always executed, which means that it does not recognize the existence of the JaccardDistance file. What am I doing wrong? Thanks in advance.

+7
matlab
source share
3 answers

For files that exist, you will return 2, not 1. You should also include the file extension in the check.

 if exist('JaccardDistance.m', 'file') == 2 

ref matlab forum Or read the manual :

exists name returns the name status:

  • 0 name does not exist.
  • 1 name is a variable in the workspace.
  • 2 One of the following is true:

    • a name exists in your MATLAB® search path as a file with the .m extension.
    • name is the name of the regular file in the MATLAB search path.
    • name is the full path to any file.
+14
source share

The exist function does not return 1, you should use

 if exist('JaccardDistance', 'file') 

Depending on which function is found, the view is returned between 1 and 8. If nothing is found, 0 is returned.

0
source share

To return 1 or 0, use

 size(dir('JaccardDistance'),1) 

i.e. if size (dir ('JaccardDistance'), 1) == 1% // you have a file, if you do not have a file

0
source share

All Articles