Search code examples
matlabmatlab-deployment

MATLAB parse OS-specific path


I am running a MATLAB project, which is shared by several users, some running Windows and some running Linux.

In some of the scripts, I need to access files which are in external directories, and which I do not want to add to the MATLAB path.

To accommodate both Linux and Windows, I need to be able to determine the type of OS I'm running, and to set the directory separator accordingly ('\' for Windows, '/' for Linux).

I tried

os = getenv('OS')

(which I saw in some official guide),but it returns an empty string.

I could check the first character of 'pwd', but that's pretty ugly, and I expect that there should be something simpler.

Thanks for any suggestions!


Solution

  • To use correct directory separator you don't need to write code to handle different operating systems. filesep gives you the correct directory separator.

    My1stDir = 'Year2012';
    My2ndDir = 'Feb';
    My3rdDir = 'Day03';
    
    MyDir = [ 'mydata', filesep, My1stDir, filesep, My2ndDir, filesep, My3rdDir ];
    

    In Linux you'll get:

    MyDir =
         mydata/Year2012/Feb/Day03
    

    In Windows you'll get:

    MyDir =
         mydata\Year2012\Feb\Day03