49

I'm working on my MATLAB code in a number of different locations, and it would really help if I could make the code aware of its location on the computer. I think there is a function that gives me exactly this information, but I can't remember what it is called or find it on Google.

The idea is that I have a function myFunc that needs a file in its own directory, which can be in different locations on different computers. So in myFunc I want to do something like this:

dir = theFunctionImLookingFor;
system(fullfile(dir, 'someApp.exe'));

(It could also be that the function I'm looking for doesn't return the directory, but the directory + m-file name, but that makes little difference to me.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jordi
  • 5,846
  • 10
  • 40
  • 41

4 Answers4

72

mfilename or better mfilename('fullpath')

Mikhail Poda
  • 5,742
  • 3
  • 39
  • 52
  • 8
    This only returns the path when running the full file. It returns an empty string when executed from the command window or when running a single cell. – anon01 Mar 11 '16 at 14:48
20

When working with classes I often like to keep associated data in the class directory. I use which to get the path and then fileparts to chop it up.

[folder, name, ext] = fileparts(which('object'));

Where 'object' can be a function or class name. The advantage of this method for me is that you can call it from outside the mfile in question. This is necessary if you need to get the path to a derived class from the base class for example.

Tom Makin
  • 3,203
  • 23
  • 23
11

Another method, via Walter Roberson on the MATLAB answers site, using the dbstack function:

S = dbstack('-completenames');
S(1).file
nibot
  • 14,428
  • 8
  • 54
  • 58
1

With the Path class you can get the file path with Path.this and the parent directory with Path.here. Use the string method to convert to a string if needed: Path.this.string.

Disclaimer: I'm the author.

MartinKoch
  • 73
  • 1
  • 5