Using `exist` to See if a Variable Exists in MATLAB

Okay, here’s a very detailed article (approximately 5000 words) on using the exist function in MATLAB to check for the existence of variables, and much more.

Using exist to See if a Variable Exists in MATLAB: A Comprehensive Guide

Introduction

In MATLAB programming, it’s frequently necessary to determine whether a variable, function, file, or other entity already exists before attempting to use it. Trying to access a non-existent variable, for example, will result in an error, halting your script’s execution. Similarly, you might want to avoid redefining an existing variable or overwriting a crucial file. The exist function in MATLAB provides a robust and versatile way to perform these existence checks, enabling you to write more reliable and error-resistant code.

This comprehensive guide will delve into all aspects of the exist function, covering its syntax, various usage scenarios, return values, performance considerations, and best practices. We’ll also explore alternatives and related functions to give you a complete understanding of how to manage variable existence in your MATLAB programs.

1. Basic Syntax and Usage

The fundamental syntax of the exist function is straightforward:

matlab
output = exist(name, type);

  • name (Required): A string (character vector) representing the name of the item you’re checking for. This could be a variable name, function name, file name (including path), class name, etc. It is important that name be a string; you cannot directly pass a variable itself.

  • type (Optional): A string specifying the type of item you’re looking for. This argument is crucial for disambiguating situations where the same name might refer to different things (e.g., a variable and a function with the same name). If type is omitted, exist searches for items in a specific order of precedence (explained later).

  • output (Return Value): A numeric value indicating whether the item exists and, if so, what type of item it is. The meaning of the output depends on the presence and value of the type argument.

2. Understanding the Return Values (without type)

When the type argument is omitted, exist(name) returns one of the following values:

  • 0: The item named name does not exist in any of the searched categories.

  • 1: name exists as a variable in the current workspace. This is the most common use case for checking variable existence.

  • 2: name exists as a file with a .m extension (an M-file) or a file with a known extension (e.g., .mat, .mex, .mdl) on the MATLAB search path, or name is the full path to a file of any type. The search path includes the current directory and any directories added using the addpath function. Crucially, this includes both script files (.m files that contain a sequence of commands) and function files (.m files that define a function).

  • 3: name exists as a MEX-file (compiled C/C++/Fortran code linked with MATLAB) on the MATLAB search path.

  • 4: name exists as a Simulink model file (.slx or .mdl) on the MATLAB search path. Note: In very old MATLAB versions, this might have returned for loaded Simulink models only. Modern versions find the files themselves.

  • 5: name exists as a built-in MATLAB function (e.g., sin, cos, plot). These are core functions of MATLAB and are always available.

  • 6: name exists as a P-code file (a pre-parsed, compiled version of an M-file with a .p extension) on the MATLAB search path. P-code files are often used to distribute code without revealing the source.

  • 7: name exists as a folder (directory).

  • 8: name exists as a class (either a built-in MATLAB class or a user-defined class).

Example (without type):

“`matlab
clear all; % Clear the workspace

myVariable = 10;

exist(‘myVariable’) % Returns 1 (variable in workspace)
exist(‘nonExistentVar’) % Returns 0 (does not exist)
exist(‘sin’) % Returns 5 (built-in function)
exist(‘myFunction.m’) % Returns 2 (if myFunction.m exists on the path)
exist(‘./myFolder’) % Returns 7 (if myFolder exists in the current directory)
exist(‘MyClass’) % Returns 8 (if MyClass is a defined class)

% Check for a file, specifying the full path
filePath = fullfile(pwd, ‘myData.txt’); % Construct full path
if exist(filePath) == 2 % or if exist(filePath, ‘file’) == 2
disp(‘File exists!’);
% Load or process the file
else
disp(‘File does not exist.’);
end

“`

3. Specifying the type Argument

The type argument significantly enhances the precision and control of exist. It allows you to specifically check for a particular type of entity, avoiding ambiguity. Here are the valid type strings:

  • 'builtin': Checks if name is a built-in MATLAB function. This is equivalent to getting a return value of 5 without the type argument.

  • 'class': Checks if name is a MATLAB class. This is equivalent to getting a return value of 8 without the type argument.

  • 'dir': Checks if name is a directory (folder). This is equivalent to getting a return value of 7 without the type argument.

  • 'file': Checks if name is a file of any type. This is the most versatile option for file checking. It encompasses M-files, MEX-files, P-code files, data files, etc., as long as the file exists on the MATLAB search path or a full path is provided. This combines the checks that would return 2, 3, 4, or 6 without the type argument.

  • 'var': Checks if name is a variable in the current workspace. This is equivalent to getting a return value of 1 without the type argument.

  • 'package': Checks if name is a MATLAB package. Packages are namespaces that organize related functions and classes.

Example (with type):

“`matlab
clear all;

myVariable = 5;

% Check specifically for a variable
if exist(‘myVariable’, ‘var’)
disp(‘myVariable exists as a variable.’);
else
disp(‘myVariable does not exist as a variable.’);
end

% Check specifically for a file (any type)
if exist(‘myScript.m’, ‘file’)
disp(‘myScript.m exists as a file.’);
else
disp(‘myScript.m does not exist as a file.’);
end

%Check for a built in function
if exist(‘mean’, ‘builtin’)
disp(‘mean is a built in function’);
end

%Check if a folder exists
if exist(‘myFolder’, ‘dir’)
disp(‘myFolder is a directory’);
end

% Check for a class
if exist(‘handle’, ‘class’)
disp(‘handle is a MATLAB class.’);
end

%Example of avoiding ambiguity.
mkdir(‘testFunction’); %Make a directory called testFunction
testFunction = 5; %make a variable called testFunction.
exist(‘testFunction’) % returns 1, because variables take precedence.
exist(‘testFunction’, ‘dir’) % returns 2.
exist(‘testFunction’, ‘var’) % returns 1.
rmdir(‘testFunction’); %clean up.
“`

4. Order of Precedence (without type)

When you call exist(name) without the type argument, MATLAB searches for name in the following order:

  1. Variable in the current workspace: MATLAB first checks if name is a variable that has been defined in the current workspace.

  2. Built-in function: Next, it checks if name is the name of a built-in function.

  3. MEX-file on the MATLAB search path.

  4. Simulink model on the MATLAB search path.

  5. P-code file on the MATLAB search path.

  6. M-file on the MATLAB search path: If name is not found as any of the above, MATLAB checks for an M-file (script or function) with the name name.m on the search path.

  7. File with any known extension.

  8. Directory: If the name refers to an existing folder.

  9. Class: Finally, it checks if name is a defined class.

This order is crucial to understand. For instance, if you have a variable named sin in your workspace, exist('sin') will return 1 (variable), not 5 (built-in function), because variables take precedence. This is why using the type argument is often recommended for clarity and to prevent unexpected behavior.

5. Checking for Multiple Items

The exist function is designed to check for a single item at a time. If you need to check for the existence of multiple variables, files, or other entities, you have several options:

  • Looping: The most straightforward approach is to use a loop (e.g., for or while) to iterate through a cell array of names and call exist for each one.

  • Cellfun: The cellfun function can apply exist to each element of a cell array, providing a more compact syntax.

  • Arrayfun: Similar to Cellfun but can be applied to other arrays not just cell arrays.

Example (Multiple Checks):

“`matlab
clear all;

varNames = {‘var1’, ‘var2’, ‘var3’, ‘nonExistentVar’};
fileNames = {‘myScript.m’, ‘data.txt’, ‘missingFile.xyz’};

% Using a loop
for i = 1:length(varNames)
if exist(varNames{i}, ‘var’)
disp([varNames{i} ‘ exists as a variable.’]);
else
disp([varNames{i} ‘ does not exist as a variable.’]);
end
end

% Using cellfun (for variables)
varExists = cellfun(@(x) exist(x, ‘var’), varNames);
disp(varExists); % Output: [0 0 0 0] (assuming none of these exist yet)

%Using cellfun (for files)
fileExist = cellfun(@(x) exist(x, ‘file’), fileNames);
disp(fileExist);

%Create those variables.
var1 = 1;
var2 = 2;
var3 = 3;
varExists = cellfun(@(x) exist(x, ‘var’), varNames);
disp(varExists); % Output: [1 1 1 0]

% Using arrayfun
% This array will have a 0 if the element is an integer, a 1 if it exists
% in the workspace
testArray = [1, 2, 3, ‘var1’];
testArrayExist = arrayfun(@(x) exist(inputname(x)), 1:numel(testArray));
disp(testArrayExist);
“`

6. Common Use Cases and Best Practices

Here are some common scenarios where exist is invaluable, along with best practices:

  • Conditional Variable Initialization: Avoid errors by checking if a variable exists before using it. If it doesn’t exist, you can initialize it with a default value.

    matlab
    if ~exist('myParam', 'var')
    myParam = 0; % Default value
    end
    % Now it's safe to use myParam
    result = myParam * 2;

  • Preventing Variable Overwriting: Check if a variable already exists before assigning a new value, especially if the existing value is important.

    matlab
    if exist('results', 'var')
    choice = input('Variable ''results'' already exists. Overwrite? (y/n): ', 's');
    if strcmpi(choice, 'y')
    results = calculateNewResults();
    else
    disp('Keeping existing ''results''.');
    end
    else
    results = calculateNewResults();
    end

  • File Input/Output Handling: Verify that input files exist before attempting to read them, and check if output files exist before writing to them (to avoid accidental overwriting).

    “`matlab
    inputFile = ‘data.csv’;
    outputFile = ‘results.txt’;

    if exist(inputFile, ‘file’)
    data = readtable(inputFile);
    else
    error(‘Input file ”%s” not found.’, inputFile);
    end

    if exist(outputFile, ‘file’)
    warning(‘Output file ”%s” already exists. It will be overwritten.’, outputFile);
    end
    writematrix(results, outputFile);
    “`

  • Function Dependency Checking: Determine if a required function (either a user-defined function or a toolbox function) is available before calling it.

    matlab
    if exist('mySpecialFunction', 'file')
    output = mySpecialFunction(inputData);
    elseif exist('imageProcessingToolboxFunction', 'file')
    output = imageProcessingToolboxFunction(inputData);
    else
    error('Required function not found.');
    end

  • Toolbox Availability: Check if a specific MATLAB toolbox is installed and licensed. This is particularly useful when distributing code that relies on optional toolboxes. This can be done with the ver function (see section 8).

  • Checking for a class definition before using it
    matlab
    if exist('MyClassName', 'class') == 8
    obj = MyClassName();
    % ... use the object ...
    else
    error('Class ''MyClassName'' is not defined.');
    end

  • Checking if a java class is on the static java path
    matlab
    if exist('com.example.MyClass', 'class') == 8
    obj = com.example.MyClass();
    % ... use the object ...
    else
    error('Class ''com.example.MyClass'' is not defined.');
    end

Best Practices:

  • Use the type argument for clarity and precision: Whenever possible, specify the type argument to avoid ambiguity and ensure you’re checking for the correct type of entity. This makes your code more readable and less prone to errors.

  • Handle missing items gracefully: Don’t just let your script crash if something doesn’t exist. Use if statements or try-catch blocks to handle cases where files are missing, variables are undefined, or functions are unavailable. Provide informative error messages or alternative execution paths.

  • Use full file paths when necessary: If you’re checking for files outside the MATLAB search path, use fullfile to construct the complete path to the file. This makes your code more robust and portable.

  • Consider performance: While exist is generally fast, excessive use in tight loops could have a minor performance impact. If performance is critical, consider caching the results of exist calls if you need to check the same item repeatedly.

  • Be aware of the search path: Understand how the MATLAB search path works and how it affects the behavior of exist. Use addpath and rmpath to manage the search path appropriately.

7. Performance Considerations

The exist function is generally very efficient, especially for checking variables in the workspace. However, its performance can vary depending on the type of item being checked and the location of the item:

  • Variables: Checking for variables in the current workspace is extremely fast.

  • Built-in functions: Checking for built-in functions is also very fast.

  • Files: Checking for files involves searching the MATLAB search path. If the file is located early in the search path or if a full path is provided, the check is relatively fast. However, if the file is located deep within the search path, or if the search path is very long, the check can take slightly longer.

  • Classes and packages: Class and package checks typically involve searching through metadata, which can be slightly slower than variable or built-in function checks.

  • Java Classes: Java classes on the static java path will be very fast, Java classes on the dynamic java path will be substantially slower.

In most cases, the performance of exist is not a significant concern. However, if you’re performing a large number of exist calls within a performance-critical loop, you might want to consider these optimizations:

  • Cache results: If you need to check for the same item multiple times within a loop, store the result of the first exist call in a variable and reuse it.

  • Use the type argument: Specifying the type can sometimes speed up the search, as exist doesn’t need to check all possible item types.

  • Minimize search path length: Keep your MATLAB search path as short as possible by removing unnecessary directories.

  • Use isfile isfolder and isvarname If you are absolutely sure of the type of item you are checking, these functions can provide additional speed.

8. Alternatives and Related Functions

While exist is the primary function for checking existence, MATLAB offers several related functions that can be useful in specific situations:

  • isfile (R2017b and later): A more specialized function specifically for checking if a file exists. It’s often slightly faster than exist(name, 'file') and more readable. It returns a logical true (1) if the file exists and false (0) otherwise. It does not distinguish between different file types.

    matlab
    if isfile('myFile.txt')
    disp('File exists.');
    else
    disp('File does not exist.');
    end

  • isfolder (R2017b and later): Similar to isfile, but specifically checks for the existence of a directory (folder). It returns true if the folder exists and false otherwise.

    matlab
    if isfolder('myDirectory')
    disp('Folder exists.');
    else
    disp('Folder does not exist.');
    end

    * isvarname This function checks if a string is a valid variable name. It does not check if the variable exists, only that it is valid to use as a name. This prevents unexpected behavior if you are, for example, constructing variable names programmatically.

    matlab
    testName = '1BadName';
    isvarname(testName) %returns 0
    testName = 'GoodName';
    isvarname('GoodName') %returns 1

  • which: Determines the full path to a function or file. If the item doesn’t exist on the MATLAB search path, which returns an empty string. You can use this in conjunction with isempty to check for existence.

    matlab
    if ~isempty(which('myFunction'))
    disp('myFunction exists.');
    else
    disp('myFunction does not exist.');
    end

  • ver: Used to check which toolboxes are available. Can also be used to get the version number of MATLAB.

    matlab
    ver %displays all installed toolboxes
    v = ver('matlab'); % Get MATLAB version information
    disp(v.Version);
    if ~isempty(ver('images'))
    disp('image processing toolbox is installed')
    end

  • try-catch: While not directly related to checking existence, the try-catch block provides a way to handle errors that might occur if you try to access a non-existent item. This is a more general error-handling mechanism.

    matlab
    try
    % Attempt to access a variable that might not exist
    value = myNonExistentVariable;
    catch ME % ME is the MException object
    if strcmp(ME.identifier, 'MATLAB:UndefinedFunction')
    disp('Variable does not exist.');
    value = 0; % Assign a default value
    else
    rethrow(ME); % Re-throw other errors
    end
    end

  • inputname: Returns the name of the variable that was passed as an input to the current function. This can be combined with exist to check if an input variable was actually provided.

    “`matlab
    function myFunction(input1, input2)
    if exist(inputname(1), ‘var’)
    disp(‘Input 1 was provided.’);
    else
    disp(‘Input 1 was not provided.’);
    end

     if exist(inputname(2), 'var')
        disp('Input 2 was provided.');
    else
        disp('Input 2 was not provided.');
    end
    

    end
    “`

  • nargin: Another important function for checking inputs. nargin gives the number of input arguments that were provided to the function.

    matlab
    function myOtherFunction(input1, input2, input3)
    if nargin < 3
    error('At least three inputs are required')
    end
    %Continue processing.
    end

    * what: lists MATLAB files in a specified folder. Useful if you want to get a complete list of all .m .mat and .mex files in a directory.

9. Advanced Usage and Special Cases

  • Checking for Variables within Functions (Local Scope): Within a function, exist checks for variables in the function’s local workspace, not the global (base) workspace. This is consistent with MATLAB’s scoping rules.

  • Checking for Variables in Nested Functions: Nested functions have access to variables in their parent functions’ workspaces. exist will correctly find variables in these enclosing scopes.

  • Checking for Properties of Objects: You can’t directly use exist to check if an object has a specific property. Instead, use the isprop function.

    matlab
    myObject = struct('field1', 1, 'field2', 2);
    if isprop(myObject, 'field3') % Correct way to check for a property
    disp('Property exists.');
    else
    disp('Property does not exist.');
    end

    * Checking for Methods of Objects: To check for the existence of a method, use the ismethod function.

  • Checking for Java classes: The exist function can also determine if a java class exists on the static java classpath. This is distinct from the dynamic classpath. The static path is set at MATLAB startup, the dynamic is changed at runtime.

10. Conclusion

The exist function is a fundamental and versatile tool in the MATLAB programmer’s arsenal. It provides a reliable way to determine the existence of variables, files, functions, classes, and other entities, enabling you to write robust, error-resistant, and well-behaved code. By understanding the nuances of exist, its return values, the optional type argument, and its interaction with the MATLAB search path, you can effectively manage variable and file dependencies, prevent unexpected errors, and create more maintainable programs. Remember to use the type argument for clarity, handle missing items gracefully, and consider performance implications when using exist extensively. Combined with related functions like isfile, isfolder, which, and try-catch, exist gives you complete control over managing the existence of various entities within your MATLAB environment.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top