Is there a function that retrieves the filename of the current script?

45 vues (au cours des 30 derniers jours)
Tobin Fricke
Tobin Fricke le 20 Juin 2011
Commenté : Chris Jennings le 24 Oct 2022
Is there a way to, from a .m file, determine the filename (including directory path) of that .m file?

Réponse acceptée

Walter Roberson
Walter Roberson le 20 Juin 2011
S = dbstack();
S(1).file
You might have to use the -completenames option.
  5 commentaires
Kevin  Hartman
Kevin Hartman le 13 Mar 2021
Additionally, S(1).name in the above example returns the filename sans extension c. MATLAB 2020b

Connectez-vous pour commenter.

Plus de réponses (3)

Kaustubha Govind
Kaustubha Govind le 20 Juin 2011
p = mfilename('fullpath')
  3 commentaires
Walter Roberson
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
Fangjun Jiang le 20 Juin 2011
I see. Thank you, Walter!

Connectez-vous pour commenter.


Eric LePage
Eric LePage le 23 Oct 2019
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
Rik
Rik le 24 Oct 2022
@Chris Jennings You can strip the path away with the fileparts function:
[FullPath,Filename,ext]=fileparts(matlab.desktop.editor.getActiveFilename)
Chris Jennings
Chris Jennings le 24 Oct 2022
perfect, thanks

Connectez-vous pour commenter.


Martin Koch
Martin Koch le 23 Oct 2022
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.

Catégories

En savoir plus sur Startup and Shutdown dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by