From: Alan B on
XYZ <junk(a)mail.bin> wrote in message <hmmsne$m6r$1(a)news.onet.pl>...
> Hi,
>
> Two questions:
> 1) How to see what's on the stack? I want to test whether a recursive
> function was called by itself or was invoked by the user/from another
> function.
>
> 2) How to get the name of a function inside the function itself?
> function abcd
> name = getFunctionName
>
> that would result in name='abcd'
>
> Thanks!

1. dbstack
2. mfilename, or d=dbstack; d(1).name

When I write a recursive function, I usually have "depth" as the last argument, which the user does NOT specify, but the function does specify in recursion calls - this way, if that argument is absent, you know the caller was not the recursive function.

Simplified example:

function r=recurse(args,depth)
if nargin<2,
depth=0;
initialize;
end
args=blah(args); % do whatever
recurse(args,depth+1) % recurse
From: XYZ on
On 04.03.2010 01:04, Alan B wrote:
> XYZ <junk(a)mail.bin> wrote in message <hmmsne$m6r$1(a)news.onet.pl>...
>> Hi,
>>
>> Two questions:
>> 1) How to see what's on the stack? I want to test whether a recursive
>> function was called by itself or was invoked by the user/from another
>> function.
>>
>> 2) How to get the name of a function inside the function itself?
>> function abcd
>> name = getFunctionName
>>
>> that would result in name='abcd'
>>
>> Thanks!
>
> 1. dbstack
> 2. mfilename, or d=dbstack; d(1).name
>
> When I write a recursive function, I usually have "depth" as the last
> argument, which the user does NOT specify, but the function does specify
> in recursion calls - this way, if that argument is absent, you know the
> caller was not the recursive function.
>
> Simplified example:
>
> function r=recurse(args,depth)
> if nargin<2, depth=0; initialize; end
> args=blah(args); % do whatever
> recurse(args,depth+1) % recurse

Thanks for the answer. The reason why I want to know who invoked the
function is that I want to PREVENT the user from specifying the last
parameter (which is only used internally for recursion purpose).
Therefore adding depth would actually result in two parameters that the
user could "accidentaly" call function with, which will result in error
at some point.
But I guess using call stack to check who invoked the function is
severely degrading performance and better solution is to use depth, or
nothing at all.