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

조회 수: 45 (최근 30일)
Is there a way to, from a .m file, determine the filename (including directory path) of that .m file?

채택된 답변

Walter Roberson
Walter Roberson 2011년 6월 20일
S = dbstack();
S(1).file
You might have to use the -completenames option.
  댓글 수: 5
Kevin  Hartman
Kevin Hartman 2021년 3월 13일
Additionally, S(1).name in the above example returns the filename sans extension c. MATLAB 2020b

댓글을 달려면 로그인하십시오.

추가 답변 (3개)

Kaustubha Govind
Kaustubha Govind 2011년 6월 20일
p = mfilename('fullpath')
  댓글 수: 3
Walter Roberson
Walter Roberson 2011년 6월 20일
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 2011년 6월 20일
I see. Thank you, Walter!

댓글을 달려면 로그인하십시오.


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

댓글을 달려면 로그인하십시오.


Martin Koch
Martin Koch 2022년 10월 23일
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.

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by