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

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.

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

Related

Function whose output is function in Julia

I am Julia user.
I want to define a function whose output is a function.
This is an example.
function get_f(p::Int)
if p == 1
return f(x) = x^2
else
return f(x) = cos(x)
return f
end
But it does not work!
f(x) = get_f(2)
f(2)
# UndefVarError x not defined.
Also, when I run the code, we have the following WARNING.
WARNING: Method definition f(Int64) in module Main at REPL[88]:4
What is the problem? If you know another good way, please tell me.
I guess we can write more sophisticated code using 'struct', but I don't know how.
We should use anonymous functions.
function get_f(p::Int)
if p == 1
return (x,y) -> x+y
elseif p == 2
return (x,y) -> norm(x-y)
else
return (x,y) -> x*y
end
end
f = get_f(2)
f(3,2) # 1.0
It works!

Why does Octave not encapsule variables inside of nested functions?

When writing nested functions in Octave, the variables do not seem to be encapsuled:
function r = asd()
fn1();
endfunction
function res1 = fn1()
res1 = 0;
function res2 = fn2()
res2 = 0;
for i = 10:20
res2 = res2 + i;
endfor
endfunction
for i = 1:10
printf("i before calling fn2(): %d\n", i);
res1 = res1 + fn2();
printf("i after calling fn2(): %d\n", i);
endfor
endfunction
This seems very odd to me because it screams for bugs, right? Is there a specific reason the variables are not encapsuled here?
Nested functions exist explicitly to share variables with the enclosing function. This is their purpose. If you don’t want a private function to share variables with the calling function, declare it after the calling function in the same M-file. This makes it a “local function”, a function only visible from within this file.
In general nested functions are weird and should only be used in specific circumstances. One place they are useful is to encapsulate variables in a more complex lambda than can be accomplished with an anonymous function:
% Returns a function that depends on x
function f = createLambda(x)
y = atan(x); % some calculation
function res = nested(val)
res = y * val; % …but this would be several lines or a loop or whatever
end
f = #nested
end
Nested functions exist in Octave because they were introduced in MATLAB. You should read the excellent MATLAB documentation to learn more about them.

Uppercase in name of a function in Julia

I am fairly new to Julia and got confused with the following code. After a function LucasTree is defined, it is used again as lt. Does Julia have some kind of role where I can recall a function using the uppercase abbreviation? If so, where can I find a nice reference for this feature?
function LucasTree(;γ = 2.0,
β = 0.95,
α = 0.9,
σ = 0.1,
grid_size = 100)
ϕ = LogNormal(0.0, σ)
shocks = rand(ϕ, 500)
# build a grid with mass around stationary distribution
ssd = σ / sqrt(1 - α^2)
grid_min, grid_max = exp(-4ssd), exp(4ssd)
grid = range(grid_min, grid_max, length = grid_size)
# set h(y) = β * int u'(G(y,z)) G(y,z) ϕ(dz)
h = similar(grid)
for (i, y) in enumerate(grid)
h[i] = β * mean((y^α .* shocks).^(1 - γ))
end
return (γ = γ, β = β, α = α, σ = σ, ϕ = ϕ, grid = grid, shocks = shocks, h = h)
end
function lucas_operator(lt, f)
# unpack input
#unpack grid, α, β, h = lt
z = lt.shocks
Af = LinearInterpolation(grid, f, extrapolation_bc=Line())
Tf = [ h[i] + β * mean(Af.(grid[i]^α .* z)) for i in 1:length(grid) ]
return Tf
end
No, this does not exist. It would be too nonunique to be practical, and moreover function names in Julia by convention should be entirely lowercase (structs/types can be CamelCase, but not functions, with the possible exception of constructors*).
In any case, all that is happening here in the code you have posted is that the function lucas_operator takes two arguments, lt and f, which can then be used within that lucas_operator function. These could in principle be anything, and regardless of what they are named outside the scope of the function, they will be named lt and f within the scope of the function. So for example:
function example(foo, bar)
return foo(2*bar)
end
if you then call
example(somereallylongfunctionname, somevariable)
then that will return the equivalent of
somereallylongfunctionname(2*somevariable)
or similarly
example(SomeImproperlyCapitalizedFunction, somevariable)
# equivalent to SomeImproperlyCapitalizedFunction(2*somevariable)
in either case, regardless of its name outside the scope of the example function, the first argument passed to the function will be known as foo within the function.
* Aside about constructors: that would be a function that is used to construct a custom type. This doesn't quite do that, but it does return an instance of a NamedTuple which then seems to be treated somewhat like a type/struct in the subsequent code, so perhaps it could be counted as a constructor.

Octave integrating

I have some problems with integrating in Octave.
I have the following code:
a=3;
function y = f (x)
y = x*x*a;
endfunction
[v,ier,nfun,err]=quad("f",0,3);
That 'a' in function is giving me troubles.
Octave says that 'a' is undefined. So, if I instead of 'a' put number 3 in function y everything works just fine. However, I want to have 'a' in function so I can change it's value.. How do I do that?
Thanks
You could use a function closure, which will encapsulate the a.
function f = makefun (a)
f = #(x) x * x * a;
endfunction
f = makefun(3)
[v, ier, nfun, err] = quad(f, 0, 3);
There are two main options.
Option 1 is, as voithos notes, make 'a' an input to the function.
Option 2 is to define 'a' to be a global variable.
global a=3;
function y = f (x)
global a
y = x*x*a;
endfunction
[v,ier,nfun,err]=quad("f",0,3);
This will cause 'a' to be the same value inside and outside the function.
Your function is actually dependent on two values, x and a, therefor:
f=#(x,a) x*x*a
[V, IER, NFUN, ERR] = quad (#(x) f(x,3), A, B, TOL, SING)
I used inline functions as i think it is easier to understand.

calling arrayfun; parameter estimation;

I have a problem with estimation.
I have a function, which is dependent on the values of an unknown vector V = [v1, …, v4].
I also have a vector of reference data YREF = [yref1, …, yrefn].
I would like to write a function, which returns the vector Y (in order to compare it later, say using lsqnonlin). I am aware of the “arrayfun”, but it seems not to work.
I have a subfunction, which returns a concrete value from the range [-100, 100],
%--------------------------------------------------------------------------
function y = SubFunction(Y, V)
y = fzero(#(x) v(1).*sinh(x./v(2)) + v(3).*x - Y, [-100 100]);
end
%--------------------------------------------------------------------------
then I make some operations on the results:
%--------------------------------------------------------------------------
function y = SomeFunction(Y,V)
temp = SubFunction (Y,V);
y = temp + v(4).*Y;
end
%--------------------------------------------------------------------------
These functions work well for a single value of Y, but not for the whole vector. How to store the results into a matrix for future comparison?
Thanks in advance
Chris
If Y is a vector, then the anonymous function defined as an argument to fzero returns a vector, not a scalar.
You can solve it by using a loop (notice the Y(k) inside the anonymous function definition):
function y = SubFunction(Y, v)
y = zeros (size(Y));
for k = 1 : length (Y)
y(k) = fzero(#(x) v(1).*sinh(x./v(2)) + v(3).*x - Y(k), [-100 100]);
end
end