nightcod3r
nightcod3r

Reputation: 792

Is it possible to know the name of the variable that provides the value in a function call in Octave?

Say that myFunction has been invoked from somewhere like this

...
myFunction (b);
...

Now, in the definition of myFunction, can I obtain the name of the variable in the call?

function myFunction (a)
  ...
  inputVble = whoscalling;   % this will result in "b"
  ...

May be it can be done if b is a global variable?

Note: this is not like in a couple other questions, where you want to know the name of the input argument, i.e. a.

Upvotes: 1

Views: 45

Answers (1)

Andy
Andy

Reputation: 8091

function ret = doit (a, b)
  inputname (1)
  inputname (2)
  ret = a + b;
endfunction

x = 4;
y = 5;
doit (x, y)

returns

ans = x
ans = y
ans =  9

But I want to mention that in my opinion, making a function somewhat dependent on the function names is bad style and shouldn't be done even if it's possible.

EDIT: I think the main reasonable use for inputname is inside a display routine for @classes. For example http://hg.savannah.gnu.org/hgweb/octave/file/51a1d1164449/examples/code/%40polynomial/display.m

function display (p)
  ...      
  fprintf ("%s =", inputname (1));

Or inside celldisp:

octave:2> a = {"huhu", pi}
a = 
{
  [1,1] = huhu
  [1,2] =  3.1416
}
octave:3> celldisp (a)
a{1} = 
huhu

a{2} = 
 3.1416

Upvotes: 3

Related Questions