Functions as arguments in gnuplot - function

In gnuplot, is there a way to pass a user defined function as an argument to another user defined function? For example, I can write a function loop which will sum shifts of a given function:
f(x) = (x <= 0) ? 0 : 1/(1+x)**2
loop(x, i, s) = (i == 0) ? f(x) : loop(x-s, i-1, s) + f(x)
Then I can do things like:
plot loop(x, 10, 1)
But, how do I define a function loop2 that does this for any function, as in something like:
loop2(g, x, i, s) = (i == 0) ? g(x) : loop2(g, x-s, i-1, s) + g(x)
so that I can then do things like:
f3(x) = (x <= 0) ? 0 : 1/(1+x)**3
plot loop2(f, x, 10, 1)
replot loop2(f3, x, 10, 1)

I think this is not possible in gnuplot 5.4.
The development version (gnuplot 5.5) has recently gained the ability to label a block of text commands as a named executable function, known as a "function block". This gives you access to commands in a function block that are not possible in a one-line user defined function. Here is your example run in a recent build of the development version. At the top level the name of the function ("f" or "f3") is passed as a parameter that can be used to construct a call of the function itself.
function $loop2(name, x, i, s) << EOF
local temp = 0
eval sprintf("temp = %s(x)", name)
return (i == 0) ? temp : temp + $loop2(name, x-s, i-1, s)
EOF
f(x) = (x <= 0) ? 0 : 1/(1+x)**2
f3(x) = (x <= 0) ? 0 : 1/(1+x)**3
set key left Left reverse
set tics nomirror
set border 3
set xrange [0:10]
set yrange [0:1.5]
plot $loop2("f", x, 10, 1), $loop2("f3", x, 10, 1)
And here is a link to an example in the demo collection that illustrates calling one function block from another, wrapping both in a top-level user defined function.
function_block demo

Related

Matlab function in fmincon with fixed value

I have a simple model where I want to minimize the RMSE between my dependent variable y and my model values. The model is: y = alpha + beta'*x.
For minimization, I am using Matlab's fmincon function and am struggling with multiplying my parameter p(2) by x.
MWE:
% data
y = [5.072, 7.1588, 7.263, 4.255, 6.282, 6.9118, 4.044, 7.2595, 6.898, 4.8744, 6.5179, 7.3434, 5.4316, 3.38, 5.464, 5.90, 6.80, 6.193, 6.070, 5.737]
x = [18.3447, 79.86538, 85.09788, 10.5211, 44.4556, 69.567, 8.960, 86.197, 66.857, 16.875, 52.2697, 93.971, 24.35, 5.118, 25.126, 34.037, 61.4445, 42.704, 39.531, 29.988]
% initial values
p_initial = [0, 0];
% function: SEE BELOW
objective = #(p) sqrt(mean((y - y_mod(p)).^2));
% optimization
[param_opt, fval] = fmincon(objective, p_initial)
If I specify my function as follows then it works.
y_mod = #(p) p(1) + p(2).*x
However, it does not work if I use the following code. How can I multiply p(2) with x? Where x is not optimized, because the values are given.
function f = y_mod(p)
f = p(1) + p(2).*x
end
Here is the output from a script that has the function declaration:
>> modelFitExample2a
RMS Error=0.374, intercept=4.208, slope=0.0388
And here is code for the above. It has many commented lines because it includes alternate ways to fit the data: an inline declaration of y_mod(), or a multi-line declaration of y_mod(), or no y_mod() at all. This version uses the multi-line declaration of y_mod().
%modelFitExample2a.m WCR 2021-01-19
%Reply to stack exchange question on parameter fitting
clear;
global x %need this if define y_mod() separately, and in that case y_mod() must declare x global
% data
y = [5.0720, 7.1588, 7.2630, 4.2550, 6.2820, 6.9118, 4.0440, 7.2595, 6.8980, 4.8744...
6.5179, 7.3434, 5.4316, 3.3800, 5.4640, 5.9000, 6.8000, 6.1930, 6.0700, 5.7370];
x = [18.3447,79.8654,85.0979,10.5211,44.4556,69.5670, 8.9600,86.1970,66.8570,16.8750,...
52.2697,93.9710,24.3500, 5.1180,25.1260,34.0370,61.4445,42.7040,39.5310,29.9880];
% initial values
p_initial = [0, 0];
%predictive model with parameter p
%y_mod = #(p) p(1) + p(2)*x;
% objective function
%If you use y_mod(), then you must define it somewhere
objective = #(p) sqrt(mean((y - y_mod(p)).^2));
%objective = #(p) sqrt(mean((y-p(1)-p(2)*x).^2));
% optimization
options = optimset('Display','Notify');
[param_opt, fval] = fmincon(objective,p_initial,[],[],[],[],[],[],[],options);
% display results
fprintf('RMS Error=%.3f, intercept=%.3f, slope=%.4f\n',...
fval,param_opt(1),param_opt(2));
%function declaration: predictive model
%This is an alternative to the inline definition of y_mod() above.
function f = y_mod(p)
global x
f = p(1) + p(2)*x;
end
carl,
The second method, in which you declare y_mod() explicitly (at the end of your script, or in a separate file y_mod.m), does not work because y_mod() does not know what x is. Fix it by declaring x global in the main program at the top, and declare x global in y_mod().
%function declaration
function f = y_mod(p)
global x
f = p(1) + p(2)*x;
end
Of course you don't need y_mod() at all. The code also works if you use the following, and in this case, no global x is needed:
% objective function
objective = #(p) sqrt(mean((y-p(1)-p(2)*x).^2));
By the way, you don't need to multiply with .* in y_mod. You may use *, because you are multiplying a scalar by a vector.

How to pass variadic arguments in Octave

I would like to implement a function duration = timer(n, f, arguments_of_f) that would measure how much time does a method f with arguments arguments_of_f need to run n times. My attempt was the following:
function duration = timer(n, f, arguments_of_f)
duration = 0;
for i=1:n
t0 = cputime;
f(arguments_of_f);
t1 = cputime;
duration += t1 - t0;
end
In another file, I have
function y = f(x)
y = x + 1;
end
The call d1 = timer(100, #f, 3); works as expected.
In another file, I have
function y = g(x1, x2)
y = x1 + x2;
end
but the call d2 = timer(100, #g, 1, 2); gives an error about undefined
argument x2, which is, when I look back, somehow expected, since I pass only
1 to g and 2 is never used.
So, how to implement the function timer in Octave, so that the call like
timer(4, #g, x1, ... , xK) would work? How can one pack the xs together?
So, I am looking for the analogue of Pythons *args trick:
def use_f(f, *args):
f(*args)
works if we define def f(x, y): return x + y and call use_f(f, 3, 4).
You don't need to pack all the arguments together, you just need to tell Octave that there is more than one argument coming and that they are all necessary. This is very easy to do using variadic arguments.
Your original implementation is nearly spot on: the necessary change is minimal. You need to change the variable arguments_to_f to the special name varargin, which is a magical cell array containing all your arbitrary undeclared arguments, and pass it with expansion instead of directly:
function duration = timer(n, f, varargin)
duration = 0;
for i=1:n
t0 = cputime;
f(varargin{:});
t1 = cputime;
duration += t1 - t0;
end
That's it. None of the other functions need to change.

In Lua, how to set a nil parameter to some default value correctly?

For Lua code below:
local function foo(x, y, z)
local x = x or true
local y = y or 1234
z = z or "default"
end
I always thought the meaning of these three lines inside the function is:
If x/y/z is nil, x/y/z is set to true/1234/"default". Otherwise, it remains whatever it is. Therefore, I have such a line in many places to set a parameter to some default value in case it might be passed into a function as nil.
However, it seems not totally correct in my experiments. I am not sure where I learnt this Lua coding concept. How to do it correctly?
The method will work as long as your boolean(?) variable x was not initialised as false. If you only want to use defaults against nil values, the a or b method is correct.
If your variable can be false, you'd have to use a strict if-then block:
if x == nil then x = true end
You can see a few more methods/examples about ternary operators on lua wiki.
There exists one more strict method if you want to be able pass nil as argument(e.g. you want distinguish foo(1,2,nil) and foo(1,2))
function foo(...)
local n,x,y,z = select('#', ...), ...
if n < 3 then z = default end
if n < 2 then y = default end
if n < 1 then x = default end
-- here x,y or z can be nil
...
end
But you have to be shure you know what you doing because it may be not expected behavior for users of your function.
This should work as expected:
function foo(x, y, z)
x = (x == nil) or x
y = (y == nil and 1234) or y
z = (z == nil and "default") or z
print(x, y, z)
end
> foo()
true 1234 default
> foo(false, false, "me")
false false me
> foo(nil, 50, "me")
true 50 me

Recursive definition of a vector

I would like to define a list using a for loop and I need to do it using a function of the n-iterate.
I have:
Initialization
In[176]: Subscript[y, 0] = {1, 2, 3}
Out[180]: {1,2,3}
The function:
In[181]: F[n_] := For[l = 1, l++, l <= 3, Subscript[y, n + 1][[l]] :=Subscript[y, n][[l]]+ n]
I call the function
F[0]
and I get:
In[183]: Subscript[y, 1]
Out[183]: Subscript[0, 1]
I should have {1,2,3}.
Anyone know why it isn't working as it should?
I have troubles recreating your error, problem.
I understand you want to add n to your vector, where n is the number of the subscript.
Here's another way to have a go at your question, avoiding the loop and the subscripts:
Clear#y;
y[0] = {1, 2, 3};
y[n_Integer] : =y[n - 1] + n
(as Plus is Listable, you can just add n to the vector, avoiding the For)
and then call it using, e.g.
y[0]
{1,2,3}
or
y[5]
{16,17,18}
Alternatively, using memoization, you could define y as follows:
y[n_Integer] := y[n] = y[n - 1] + n
This will then store already calculated values (check ?y after executing e.g. y[5]). Don't forget to Clear y, if y changes.
Obviously, for a function as this one, you might want to consider:
y[n_Integer] := y[0] + Total[Range[n]]

How can you emulate recursion with a stack?

I've heard that any recursive algorithm can always be expressed by using a stack. Recently, I've been working on programs in an environment with a prohibitively small available call stack size.
I need to do some deep recursion, so I was wondering how you could rework any recursive algorithm to use an explicit stack.
For example, let's suppose I have a recursive function like this
function f(n, i) {
if n <= i return n
if n % i = 0 return f(n / i, i)
return f(n, i + 1)
}
how could I write it with a stack instead? Is there a simple process I can follow to convert any recursive function into a stack-based one?
If you understand how a function call affects the process stack, you can understand how to do it yourself.
When you call a function, some data are written on the stack including the arguments. The function reads these arguments, does whatever with them and places the result on the stack. You can do the exact same thing. Your example in particular doesn't need a stack so if I convert that to one that uses stack it may look a bit silly, so I'm going to give you the fibonacci example:
fib(n)
if n < 2 return n
return fib(n-1) + fib(n-2)
function fib(n, i)
stack.empty()
stack.push(<is_arg, n>)
while (!stack.size() > 2 || stack.top().is_arg)
<isarg, argn> = stack.pop()
if (isarg)
if (argn < 2)
stack.push(<is_result, argn>)
else
stack.push(<is_arg, argn-1>)
stack.push(<is_arg, argn-2>)
else
<isarg_prev, argn_prev> = stack.pop()
if (isarg_prev)
stack.push(<is_result, argn>)
stack.push(<is_arg, argn_prev>)
else
stack.push(<is_result, argn+argn_prev>)
return stack.top().argn
Explanation: every time you take an item from the stack, you need to check whether it needs to be expanded or not. If so, push appropriate arguments on the stack, if not, let it merge with previous results. In the case of fibonacci, once fib(n-2) is computed (and is available at top of stack), n-1 is retrieved (one after top of stack), result of fib(n-2) is pushed under it, and then fib(n-1) is expanded and computed. If the top two elements of the stack were both results, of course, you just add them and push to stack.
If you'd like to see how your own function would look like, here it is:
function f(n, i)
stack.empty()
stack.push(n)
stack.push(i)
while (!stack.is_empty())
argi = stack.pop()
argn = stack.pop()
if argn <= argi
result = argn
else if n % i = 0
stack.push(n / i)
stack.push(i)
else
stack.push(n)
stack.push(i + 1)
return result
You can convert your code to use a stack like follows:
stack.push(n)
stack.push(i)
while(stack.notEmpty)
i = stack.pop()
n = stack.pop()
if (n <= i) {
return n
} else if (n % i = 0) {
stack.push(n / i)
stack.push(i)
} else {
stack.push(n)
stack.push(i+1)
}
}
Note: I didn't test this, so it may contain errors, but it gives you the idea.
Your particular example is tail-recursive, so with a properly optimising compiler, it should not consume any stack depth at all, as it is equivalent to a simple loop. To be clear: this example does not require a stack at all.
Both your example and the fibonacci function can be rewritten iteratively without using stack.
Here's an example where the stack is required, Ackermann function:
def ack(m, n):
assert m >= 0 and n >= 0
if m == 0: return n + 1
if n == 0: return ack(m - 1, 1)
return ack(m - 1, ack(m, n - 1))
Eliminating recursion:
def ack_iter(m, n):
stack = []
push = stack.append
pop = stack.pop
RETURN_VALUE, CALL_FUNCTION, NESTED = -1, -2, -3
push(m) # push function arguments
push(n)
push(CALL_FUNCTION) # push address
while stack: # not empty
address = pop()
if address is CALL_FUNCTION:
n = pop() # pop function arguments
m = pop()
if m == 0: # return n + 1
push(n+1) # push returned value
push(RETURN_VALUE)
elif n == 0: # return ack(m - 1, 1)
push(m-1)
push(1)
push(CALL_FUNCTION)
else: # begin: return ack(m - 1, ack(m, n - 1))
push(m-1) # save local value
push(NESTED) # save address to return
push(m)
push(n-1)
push(CALL_FUNCTION)
elif address is NESTED: # end: return ack(m - 1, ack(m, n - 1))
# old (m - 1) is already on the stack
push(value) # use returned value from the most recent call
push(CALL_FUNCTION)
elif address is RETURN_VALUE:
value = pop() # pop returned value
else:
assert 0, (address, stack)
return value
Note it is not necessary here to put CALL_FUNCTION, RETURN_VALUE labels and value on the stack.
Example
print(ack(2, 4)) # -> 11
print(ack_iter(2, 4))
assert all(ack(m, n) == ack_iter(m, n) for m in range(4) for n in range(6))
print(ack_iter(3, 4)) # -> 125