Search code examples
matlabfunctionparent

Know the parent function


I'm wondering if there is a way to know by what function is called my function "fun_a" when running fun_a. I know that i could track the "parent function" by sending information as an argument to the "child function" but i would like to avoid that if possible.

Thanks a lot


Solution

  • One way is using dbstack:

    % In a sub-function or function called by another
    st = dbstack;
    st(1).name % The function's name
    st(2).name % The function caller's name (parent)
    ...
    

    Another useful function is mfilename if you happen to just want the name of the main function and M-file in which a sub-function resides.

    No idea what the computational cost of these are, but I imagine that simply passing in the function name is going to be cheaper even if less elegant.