Is there a function that retrieves the filename of the current script?
Afficher commentaires plus anciens
Is there a way to, from a .m file, determine the filename (including directory path) of that .m file?
Réponse acceptée
Plus de réponses (3)
Kaustubha Govind
le 20 Juin 2011
p = mfilename('fullpath')
3 commentaires
Fangjun Jiang
le 20 Juin 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
le 20 Juin 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
le 20 Juin 2011
I see. Thank you, Walter!
Eric LePage
le 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 commentaires
Walter Roberson
le 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
le 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
le 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
le 30 Août 2021
matlab.desktop.editor.getActiveFilename
Chris J
le 24 Oct 2022
Thanks Paul, that works.
However it returns the entire path. Is there an way to return the filename only?
Rik
le 24 Oct 2022
[FullPath,Filename,ext]=fileparts(matlab.desktop.editor.getActiveFilename)
Chris J
le 24 Oct 2022
perfect, thanks
Martin Koch
le 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.
Catégories
En savoir plus sur Live Scripts and Functions dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!