exist

Checks whether a variable, file, folder or function exists, and what kind it is.

Category: Programming > Files and Folders

Syntax

n = exist(name)

Searches variables first, then files, folders and functions, and returns a code.

n = exist(name, type)

Restricts the search to 'var', 'file', 'dir' or 'builtin'.

Description

The numeric code tells the kind of item, and zero means nothing was found. A variable in the workspace wins over a file of the same name unless type says otherwise. File names are resolved against the current folder and the path.

For tests that only need a yes or no, isfile, isfolder and isvarname are clearer, and isfile and isfolder do not search the path.

Input arguments

name
Name to look for, as text.
type
Optional category: 'var', 'file', 'dir' or 'builtin'.

Output arguments

n
0 not found, 1 variable, 2 file, 5 built-in function, 7 folder.

Example

Codes for different kinds of item

x = 1;
writelines('hi', 'note.txt');
mkdir results
[exist('x'), exist('note.txt'), exist('results'), exist('sin'), exist('nothing_here')]
exist('results', 'dir')
Output
ans = 1×5

     1     2     7     5     0
ans = 7

Notes

MatLivre reports 5 for every function it implements natively, including some that are M-files in MATLAB (for example median, which MATLAB reports as 2).

See also

isfile isfolder which isvarname who