MATLAB analyzes OS-specific path

I am launching a MATLAB project that is used by several users, some of whom are running Windows and some running Linux.

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

To host both Linux and Windows, I need to determine the type of operating system that I am running and set the directory separator accordingly ('\' for Windows, '/' for Linux).

I tried

os = getenv('OS')

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

I could check the first β€œpwd” character, but it's pretty ugly, and I expect there should be something simpler.

Thanks for any suggestions!

+3
source share
1 answer

To use the correct directory separator, you do not need to write code to work with various operating systems. filesepprovides the correct directory separator.

My1stDir = 'Year2012';
My2ndDir = 'Feb';
My3rdDir = 'Day03';

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

On Linux, you get:

MyDir =
     mydata/Year2012/Feb/Day03

On Windows, you will get:

MyDir =
     mydata\Year2012\Feb\Day03
+6
source

All Articles