Loren on the Art of MATLAB

Turn ideas into MATLAB


Loren on the Art of MATLAB has been archived and will not be updated.

Machine-Independent Filenames

When developing applications is MATLAB, I often find myself interacting with files, sometimes data, sometimes algorithms. In order to be sure I am operating with the correct file, for example for loading data, I want to use the full path. However, I also want to pass my program on to other users, and their path information might not match mine.


Recent Example at The MathWorks

Recently at The MathWorks, someone wanted to share some files with another person so they could discuss the content. To do so, the author provided code that looked like this. Here YEAR is a variable of class char.


You might wonder what the problem with this is. Well, for one thing, the author works on a Windows platform, but the recipient frequently does not. So how could this code have been written differently?

The T:\ drive maps to a file server that is accessible from any of our networked computers. So one possibility is to write code something like this:

      baseLocationWin = 'T:\';
      baseLocationOther = '//home/tester';
      if ispc  % true for windows platforms
          baseLocation = baseLocationWin;
          baseLocation = baseLocationOther;
      path1 = '1-36U6NN';
      YEAR = '2001';
      fname = ['secprd' YEAR '.txt'];
      fullfname = fullfile(baseLocation, path1, fname);

On Windows, where I ran this code, here's the file name.


The equivalent UNIX pathname would be

disp([baseLocationOther '/' path1, '/' fname])

Reference Material

Here you'll see a list of some MATLAB functions that are useful in writing machine independent applications when it comes to referring to files.


Have you been in this situation? Do you have other techniques to help users write robust code for handling files? If so, please post here.

Published with MATLAB® 7.4

  • print


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