exist — Determine whether variables, files, folders, or symbols exist in MATLAB and RunMat.
exist(name) returns an integer code identifying whether a named variable, file, folder, builtin, class, or related symbol is available. Optional type filters and return-code behavior follow MATLAB and RunMat lookup semantics.
Syntax
code = exist(name)
code = exist(name, type)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
name | Any | Yes | — | Variable/function/file/class name to query. |
type | StringScalar | Yes | — | Query kind: var|file|dir|builtin|class|handle|method|mex|pcode|simulink|thunk|lib|java. |
Returns
| Name | Type | Description |
|---|---|---|
code | NumericScalar | Existence code (0,1,2,3,4,5,6,7,8) following MATLAB semantics. |
Errors
| Identifier | When | Message |
|---|---|---|
| — | More than two total input arguments are provided. | exist: too many input arguments |
| — | Name input is not a character vector or string scalar/array scalar. | exist: name must be a character vector or string scalar |
| — | Type input is not a character vector or string scalar/array scalar. | exist: type must be a character vector or string scalar |
| — | Type input is not one of the supported exist query types. | exist: invalid type. Type must be one of 'var', 'variable', 'file', 'dir', 'directory', 'folder', 'builtin', 'built-in', 'class', 'handle', 'method', 'mex', 'pcode', 'simulink', 'thunk', 'lib', 'library', or 'java' |
How exist works
- Searches follow MATLAB's precedence: variables first, then built-ins, classes, compiled code (MEX/P-code), standard files, and finally folders.
- When you omit the type,
existreturns the first match respecting this precedence. - String handling matches MATLAB:
nameand the optionaltypemust be character vectors or string scalars. String arrays must contain exactly one element. - Paths expand
~to the user's home folder. Relative paths resolve against the current working directory, and RunMat honoursRUNMAT_PATH/MATLABPATHentries when searching for scripts and classes. - Package-qualified names such as
pkg.funcandpkg.Classmap to+pkgfolders automatically. Class queries also recognise@ClassNamefolders and.mfiles that containclassdef. - GPU-resident arguments (for example,
gpuArray("script")) are gathered automatically, so callers never need to move text back to the CPU manually. - Unsupported second-argument types surface a MATLAB-compatible error listing the accepted keywords.
Does RunMat run exist on the GPU?
The builtin runs entirely on the host CPU. If any argument lives on the GPU, RunMat gathers it to host memory before performing the lookup. Providers do not implement dedicated hooks for exist, and the result is always returned as a host-resident double scalar. Documented behaviour is identical regardless of whether acceleration is enabled.
GPU memory and residency
No. exist gathers any GPU-resident string inputs transparently. The lookup, file system checks, and return value are always host-side operations. Keeping text on the GPU offers no performance benefits, so you can pass regular character vectors or string scalars.
Examples
How to check if a workspace variable exists
alpha = 3.14;
status = exist("alpha", "var")Expected output:
status =
1How to determine if a built-in function is available
code = exist("sin")Expected output:
code =
5How to test whether an M-file is on the MATLAB path
status = exist("utilities/process_data", "file")Expected output:
status =
2How to verify a folder exists before creating logs
mkdir("logs");
status = exist("logs", "dir")Expected output:
status =
7How to detect class definitions in packages
status = exist("pkg.Widget", "class")Expected output:
status =
8How to inspect compiled MEX fallbacks
if exist("fastfft", "mex")
disp("Using compiled fastfft.");
else
disp("Falling back to MATLAB implementation.");
endExpected output:
% Prints which implementation will be executed based on the presence of fastfft.mex*.Using exist with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how exist changes the result.
Run a small exist example, explain the result, then change one input and compare the output.
FAQ
Does exist support wildcards?⌄
No. Strings containing * or ? return 0, matching MATLAB behaviour.
What about Simulink models or Java classes?⌄
RunMat reports 4 for .slx / .mdl files. Java class detection is not implemented yet and currently returns 0, mirroring MATLAB when Java support is unavailable.
How are packages handled?⌄
Names like pkg.func translate to +pkg/func.m. Class queries additionally search +pkg/@Class folders.
Is the search path configurable?⌄
Yes. RunMat honours the current working directory plus any folders listed in RUNMAT_PATH or MATLABPATH (path separator aware).
What's the search precedence when multiple items share a name?⌄
Variables have highest priority, followed by built-ins, classes, compiled code (MEX/P-code), standard files, and folders last—exactly like MATLAB.
What happens with unsupported type keywords?⌄
The builtin raises exist: invalid type... describing the accepted tokens, matching MATLAB's diagnostic.
Do handle queries work?⌄
When the first argument is a RunMat handle object, exist(handle, "handle") returns 1. Numeric graphics handles are not yet supported and return 0.
What does exist do in MATLAB?⌄
exist(name, type) checks whether a variable, file, folder, or function named name exists and returns a numeric code indicating what kind of item was found. Zero means nothing was found.
How do I check if a file exists in MATLAB?⌄
Use exist('filename.m', 'file'). It returns 2 if the file is found on the MATLAB path, or 0 if not found. In RunMat, the same syntax works.
What are the return codes for exist in MATLAB?⌄
exist returns 0 (not found), 1 (variable in workspace), 2 (file on path), 3 (MEX file), 4 (Simulink model), 5 (built-in function), 7 (folder), or 8 (Java class). RunMat supports codes 0, 1, 2, 5, and 7.
What does each exist return value mean?⌄
— The complete MATLAB table is:
| Code | Meaning | |------|---------| | 0 | Not found | | 1 | Variable in the active workspace | | 2 | File (including .m scripts, .mat, and most data files on the path) | | 3 | MEX-file (compiled C/C++/Fortran) | | 4 | Simulink model (.slx / .mdl) | | 5 | Built-in function | | 6 | P-code file (.p) | | 7 | Folder | | 8 | Class (classdef or @Class folder) |
Use the two-argument form (exist(name, 'file'), exist(name, 'dir'), exist(name, 'builtin'), exist(name, 'class')) when you want to restrict the search to a single kind.
How do I check if a variable or file exists before using it?⌄
— Use the two-argument form so the result is unambiguous:
if exist('myVar', 'var')
disp(myVar);
end
if exist('data.mat', 'file')
load('data.mat');
endFor files specifically, isfile('data.mat') and isfolder('outdir') return plain logicals and are often clearer than exist alone.
How do I create a folder only if it doesn't already exist?⌄
— Combine exist with mkdir:
if ~exist('outdir', 'dir')
mkdir('outdir');
endA newer, equally idiomatic alternative is if ~isfolder('outdir'), mkdir('outdir'); end. mkdir itself is a no-op when the folder already exists (it just prints a warning), so either pattern is safe.
Related Io functions
Repl Fs
addpath · cd · copyfile · delete · dir · fullfile · genpath · getenv · ls · mkdir · movefile · path · pwd · rmdir · rmpath · run · savepath · setenv · tempdir · tempname
Tabular
csvread · csvwrite · dlmread · dlmwrite · readmatrix · writematrix
Filetext
fclose · feof · fgetl · fgets · fileread · filewrite · fopen · fprintf · fread · frewind · fwrite
Json
Http
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how exist is executed, line by line, in Rust.
- View the source for exist in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.