Is there a function that retrieves the filename of the current script?
Show older comments
Is there a way to, from a .m file, determine the filename (including directory path) of that .m file?
Accepted Answer
More Answers (3)
Kaustubha Govind
on 20 Jun 2011
p = mfilename('fullpath')
3 Comments
Fangjun Jiang
on 20 Jun 2011
mfilename() is right function to call. You can simply have this line in your .m file to get the file name.
P=mfilename;
Walter Roberson
on 20 Jun 2011
mfilename does not include the extension, and thus cannot distinguish between .p and .m files.
mfilename without any option does not include the path as was specifically requested by the user.
Fangjun Jiang
on 20 Jun 2011
I see. Thank you, Walter!
Eric LePage
on 23 Oct 2019
0 votes
I'd appreciate a qualification, because what I get for R2019b is not very helpful; it certainly isn't the name of the currently running mfile. Thanks.
P = mfilename
P =
'LiveEditorEvaluationHelperESectionEval67edf31d'
or
S = dbstack();
>> S(1).file
ans =
'LiveEditorEvaluationHelperESectionEval67edf31d.mlx'
8 Comments
Walter Roberson
on 23 Oct 2019
Live editor creates temporary files containing just the section of code to be evaluated, and runs those. It does not execute the .mlx directly -- and in fact .mlx files are zip archives containing all of the code plus the output and various special sections for annotations and so on.
Saying which file is executing is more difficult for LiveScript.
In the special case where what you want is the name of the LiveScript, it just might be possible to use editor facilities to fetch it, perhaps.
Eric LePage
on 24 Oct 2019
Thanks Walter for your response. The puzzle is that I'm not using Live editor at all. I hate to admit it, but coming to terms with Live Editor seems like a large mental hurdle, the climbing of which I can postpone until after certain targets are met. Why therefore doesn't mfilename() behave well as it always has?
Walter Roberson
on 24 Oct 2019
You are using Run Section. It does the same thing: writes the code into a temporary file and runs the temporary file. If you were to use just Run (of the whole .m file) then the mfilename would work.
Paúl Aguilar
on 30 Aug 2021
matlab.desktop.editor.getActiveFilename
Chris J
on 24 Oct 2022
Thanks Paul, that works.
However it returns the entire path. Is there an way to return the filename only?
Rik
on 24 Oct 2022
[FullPath,Filename,ext]=fileparts(matlab.desktop.editor.getActiveFilename)
Chris J
on 24 Oct 2022
perfect, thanks
Martin Koch
on 23 Oct 2022
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.
Categories
Find more on Live Scripts and Functions in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!