Loren on the Art of MATLAB

February 1st, 2006

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 = '';
     end
end

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.

12 Responses to “Existence in MATLAB”

  1. david replied on :

    Hello.

    Great blog. It is really helpfull with some aspects of Matlab.
    I would like to ask you if it is possible to control a device with matlab or “data acquisition toolbox” trough the serial port RS-232.

    thank you.

  2. loren replied on :

    You can in MATLAB or the Instrument Control Toolbox. A good place to look for this sort of information is The MathWorks support page. You can search for the function serial and read the documentation beyond the reference pages. There are also some illustrative demo pages.

  3. peter replied on :

    Yes, but what about

    myFile = [path filesep 'foo.mat'];
    if ~exist(‘myFile’, ‘file’)
    %create the file
    end

    This fails, because Matlab returns 0, thinking that myFile is a var (which it is, but it’s also a file). Hardcoding the string, of course, works.

  4. Saadia Iftikhar replied on :

    How to deal with problem which Peter addressed? If File is in MAT format and want to check its existence? How to do this?

    peter replied on October 4th, 2006 at 7:49 pm :

    Yes, but what about

    myFile = [path filesep ‘foo.mat’];
    if ~exist(’myFile’, ‘file’)
    %create the file
    end

  5. Loren replied on :

    Saadia and Peter-

    The problem is, you have a created a variable called myFile so asking if it exists gets things in a mess. And there probably isn’t a file itself named ‘myFile’ but the contents of myFile. You need to do this:

    if exist(myFile,’file)

    which will use the contents of the variable myFile

    or you might be able to use which, but in functional form

    which(myFile)

    and see if it returns empty or not (though I don’t think which will work for something not on the matlabpath).

    –Loren

  6. Hannah replied on :

    Hi,

    Is there any way to check for the existence of structure elements?

    For example…

    >> c
    c =
    cheese: ‘gruyere’
    wine: ‘sauvignon blanc’
    >> d
    d =
    wine: ‘sauvignon blanc’
    >> if (exist(‘c.cheese’)) disp(c.cheese); else disp(‘no cheese here’); end
    no cheese here
    >> if (exist(‘d.cheese’)) disp(d.cheese); else disp(‘no cheese here’); end
    no cheese here

  7. Loren replied on :

    Hannah-

    If you are looking to see if a value of a field is set, use one of the string comparison functions, e.g.,

    if strcmp(c.cheese,'gruyere')
       disp('Thank you')
    else
       disp('How disappointing!')
    end
    

    and if you are looking to see if the field exists, use isfield

    if isfield(c,'cheese')
       if strcmp(c.cheese,'gruyere')
          disp('Thank you')
       else
          disp('How disappointing!')
       end
       disp('no cheese here')
    end
    

    –Loren

  8. Sung Soo replied on :

    What a cool feature. As an old MATLAB user, I wanted this feature for a long time, but I’ve not noticed that it’s been already implemented long time ago. I had to find your blog earlier…

  9. Aramendi replied on :

    Peter & Saadie, i had the same problem: how checking existence of a MAT file, and I have to say that

    exist([filepath,'filename.mat'])

    works for me, returning a 2 (not a 0).

  10. Eric Jaquay replied on :

    Hi,

    So I’m having a similar problem to Peter’s, but I actually want to check for the existence of a file, not its contents. I’m using MATLAB to control the submission of jobs to a cluster, and I don’t want to proceed to the next step in my MATLAB code (which is to interpret the output of the cluster job) until it finishes.

    ctlfile=['optimize' num2str(counter) '.ctl'];   outfile=['optimize' num2str(counter) '.out'];    runmeepcmd=['runmeep-mpi ' ctlfile ' ' outfile ' 30:00 32 2'];
    unix(runmeepcmd);
    [status,jobID]=unix('qstat -u jaquay | cut -c 1-7 | sed -n -e ''6 p''');
    outputfilename=['optimize' num2str(counter) '.pbs.e' num2str(jobID)''];
    pause(300)
    while exist(outputfilename,'file') == 0
         pause(300)
         disp('still waiting')
    end
    

    Using exist with a single argument, outputfilename, returns a 1 because the variable exists in the workspace. Using the 2nd argument and forcing it to look for a file with that name returns 0, even though I can see the file in the directory (and ‘ls’ in MATLAB shows me that file).

    Any ideas? A simpler way, perhaps?

    Thanks.

  11. Loren replied on :

    Eric-

    The way to check for a file is using exist. You may need to wait, as you do with the pause, to let the OS catch up. Another way to check is to use the dir function, checking the return values. If you can’t get this to work, I suggest contacting support (link on the right).

    exist with a single argument looks for the argument. Do you try exist(arg) or exist(‘arg’)? That can confuse people… exist(‘arg’) looks for the literal string ‘arg’ and exist(arg) looks for whatever the variable arg refers to. So if using exist(arg), it doesn’t automatically return 1.

    –loren

  12. Eric Jaquay replied on :

    Thanks for your response, Loren. I’m running an optimization, and each pass of my MATLAB loop launches a new cluster job. As a result, the filename that I need to look for is changing each time, albeit in a fairly predictable way. Thus, I check for the filename with this statement

    outputfilename=['optimize' num2str(counter) '.pbs.e' num2str(jobID)''];

    which of course creates the variable, then do

    exist(outputfilename,’file’)

    (I’ve actually tried it with and without the quotes around outputfilename — in neither case does it work, but I think the correct syntax is without. In this case, the variable outputfilename is a string representing the filename.)

    A typical file name that I want to check for is something like optimize34.pbs.e7765493, which means that it’s the 34th iteration of my MATLAB loop, which submitted a job that was auto-assigned jobID 7765493 on the cluster. Once the job is finished this file is generated, and then MATLAB can import/process the data in the remainder of the loop. The pause(300) is there because the job takes some time to finish on the cluster, and I’m only checking every 5 minutes to see if it’s done.

    Anyway, I’ll see if I can get it work using dir. Thanks for the suggestion (I’m of course open to others, too.)

    Best,
    Eric


MathWorks
Loren Shure works on design of the MATLAB language at MathWorks. She writes here about once a week on MATLAB programming and related topics.

These postings are the author's and don't necessarily represent the opinions of The MathWorks.