Loren on the Art of MATLAB

Turn ideas into MATLAB

Existence in MATLAB

Users have needed access to information about the existence of variables, files, etc. in MATLAB for a long time. The function exist allows us to programmatically check for these entities.

exist can be called with one argument (a string) to test if that specific name is known and available in MATLAB in any form. If we program carefully and check the output result of exist, then we can be sure we know whether we are dealing with a MATLAB variable, a Simulink model, etc.

I often see user's calling exist with a single input argument, a name. This answers whether or not that name is somehow in the MATLAB environment. Very often, however, we really want more specific information, such as whether or not that name refers to a variable. A careful check of the output value (not just >0) can supply this information, though I rarely see code check for this.

Using the two input syntax for exist, we are able to write code that is both more robust, more readable, and frequently more efficient.

For example, if we have a program in which we ask the user to type in a variable name to process, we may then want to verify that the variable exists or else prompt the user again for a valid variable name. To do so, we might write code like this:

varname = '';
while isempty(varname)
     varname = input('Which variable would you like to process?','s');
     if ~exist(varname,'var')
         varname = '';

When we run this code, since we are only checking for variables, MATLAB does not need to go look on the file system for all the other possible items MATLAB might be interested in such as M-Files, etc. This can result in a tremendous speed gain! And, by confining the search to variables, the code is more robust since it can't get misled if the name refers to an M-File.



To leave a comment, please click here to sign in to your MathWorks Account or create a new one.