How to get the file path inside a script, function, or model?

조회 수: 90 (최근 30일)
MathWorks Support Team
MathWorks Support Team 2019년 4월 18일
편집: dzid_ 2020년 11월 25일
How can I get the path of the script or function being executed or model being run from inside the file itself?

채택된 답변

MathWorks Support Team
MathWorks Support Team 2019년 7월 26일
편집: MathWorks Support Team 2019년 7월 26일
For scripts and functions:
[filepath,~,~] = fileparts(mfilename('fullpath'))
or simply
filepath = fileparts(mfilename('fullpath'))
Note:
-This works with M file scripts and functions during normal execution.
-This will not produce the desired result for MLX live scripts or in "%%" sections of scripts run individually.
-The functions used are not supported for code generation.
For live scripts (or "%%" sections of scripts):
[filepath,~,~] = fileparts(which('your_file_name'))
or simply
filepath = fileparts(which('your_file_name'))
Note:
-This requires manually entering the name of the file into 'your_file_name'.
-The more flexible approach which works for M file scripts and functions using 'mfilename' returns incorrect results for MLX live scripts and "%%" sections of scripts run individually.
-The functions used are not supported for code generation.
For Simulink models:
[path,~,~] = fileparts(which(bdroot))
or simply
path = fileparts(which(bdroot))
Note:
-This can be used in Model Callbacks, Block Callbacks, Mask Initialization, and Mask Icon & Ports.
-Using "gcs" in place of "bdroot" will not give the desired result in some circumstances, for example Block Callbacks inside subsystems.
-The functions used are not supported for code generation.
  댓글 수: 1
dzid_
dzid_ 2020년 11월 25일
편집: dzid_ 2020년 11월 25일
which(bdroot)
Doesn't work if model is not in the path.
Instead, use:
get_param(bdroot, 'FileName');

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Simulink Environment Customization에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by