How to check if a file exists in Matlab? [closed]

半世苍凉 提交于 2021-02-16 06:16:12

问题


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

The file JaccardDistance is in the same folder where this code is being executed. The problem is that the "else" part is always being executed, which means that it is not recognizing that the file JaccardDistance exists. What am I doing wrong? Thanks in advance.


回答1:


For files you exists will return a 2 not a 1. You should also include the file extension in the check.

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

ref matlab forum Or read the manual:

exist name returns the status of name:

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

    • name exists on your MATLAB® search path as a file with extension .m.
    • name is the name of an ordinary file on your MATLAB search path.
    • name is the full pathname to any file.



回答2:


The exist function does not return a 1, you have to use

if exist('JaccardDistance', 'file')

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




回答3:


To return 1 or 0 use

size(dir('JaccardDistance'),1)

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



来源:https://stackoverflow.com/questions/34092819/how-to-check-if-a-file-exists-in-matlab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!