How can we know whether the current execution of command is conducting inside a function or not?

조회 수: 6 (최근 30일)
How can we know whether the current execution of command is conducting inside a function or not?
When I develop a function, I frequently check some parts of the code for the function in base command envirenment.
I wonder is there any method to identify whether the current execution is conducting inside of a function or
it is conducting in the base environment.
Thanks in advance !!!

채택된 답변

Walter Roberson
Walter Roberson 2021년 10월 23일
편집: Walter Roberson 2021년 10월 23일
The functions nargin and nargout will error if executed at the base. So you can use try/catch
inbase = false; try; nargin; catch ME; inbase = true; end

추가 답변 (1개)

Image Analyst
Image Analyst 2021년 10월 23일
편집: Image Analyst 2021년 10월 23일
You can call fprintf immediately upon entering and just befor leaving the function:
fprintf('Entering MyFunction().\n');
fprintf('Leaving MyFunction().\n');
If you stop at a break point, you can check the call stack on the tool bar. Or you can get the call stack from my attached function and print it out inside the function.
  댓글 수: 5
Saang Bum Kim
Saang Bum Kim 2021년 10월 24일
편집: Saang Bum Kim 2021년 10월 24일
As I understand the attached file, GetCallStack.m, runs like,
try
% Some code that might throw an error......
catch ME
callStackString = GetCallStack(ME);
end
I think that the dbstack() what @Stephen suggested could similar works more easily.
I fount that the modified method from what @Stephen suggested works well until now:
~(length({output(@() dbstack,1).name})-2)
Image Analyst
Image Analyst 2021년 10월 24일
@Saang Bum Kim, okay. I don't see Stephen on this thread, but it looks like you've accepted the Answer from Walter so I guess everything is figured out and working now. Best wishes.

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

카테고리

Help CenterFile Exchange에서 Historical Contests에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by