Writing simple equations in Octave - octave

Imagine I want to define a function in Octave z(var1, var2) = a(var1) + b(var1) + c(var2) + d(var2) + const. Prior to this definition, I would like to define all the neccessary functions, something like: a(var1) = var1^2 + const, b(var1) = cos(var1), c(var) = sqrt(var2 - const) etc. Later in time, I add all those functions and form the final one, z function. Afterwards, I'd like to get partial derivatives of the function z in respect to var1 and var2.
So far, my only concern is defining the functions above to work as i imagined; is it possible and how ?

You can use function handles and anonymous functions:
a = #(x) x^2 + c1;
b = #cos;
c = #(x) sqrt(x - c2);
d = #exp;
b and d are handles to existing functions. You can call them as regular functions using b(...) or d(...). a and c are anonymous functions. They provide the argument list and definition of the handle right there in the assignment, somewhat like Python's lambdas. You could do something like b = #(x) cos(x), but there is really no point since there are no additional operations necessary.
Now you can do
z = #(x, y) a(x) + b(x) + c(y) + d(y) + c3;
The alternative is to write separate m-files for each function, which I am assuming you would like to avoid.
Using the function, for example to take partial derivatives, is now fairly straightforward. Function handles are called just like any other builtin or m-file-defined function:
(z(x + delta, y) - z(x - delta, y)) / (2 * delta)
Update
Just for fun, I ran the following script (using Octave 3.4.3 on Red Hat 6.5):
octave:1> c1 = -100;
octave:2> c2 = -10;
octave:3> c3 = 42;
octave:4> a = #(x) x^2 + c1;
octave:5> b = #cos;
octave:6> c = #(x) sqrt(x - c2);
octave:7> d = #exp;
octave:8> z = #(x, y) a(x) + b(x) + c(y) + d(y) + c3;
octave:9> [X, Y] = meshgrid([-10:0.1:10], [-10:0.1:10]);
octave:10> surf(X, Y, z(X, Y));
The result is not especially interesting, but it does demonstrate the effectiveness of this technique:
Here is an IDEOne link to play with.

Related

how to create multivariate function handle in matlab in this case?

I would like to create a multivariate functional handle which the number of variables is changeable according to the input.
First, create n symbolic variables, and note that n can be changed according to your input.
n=3;
syms theta [1 n];
Now I create a function g. Via For loop, create the summation of g on all theta. As seen in the code, f is a symbolic expression.
g = #(x)(x^2);
f = 0;
for i = 1:n
f = f + g(sym(sprintfc('theta%d',i)))
end
Now I want to create a functional handle F according to f.
One potential way to do this F = #(theta1,theta2,theta3)(f). However, since n is user-specified, changeable variable, this approach is not doable.
Could someone give my hint? Many thanks!
Is this what you are looking for?
g = #(x)x.^2
fn = #(varargin) sum( cellfun(g,varargin) )
Now we have an anonymous function with a variable number of inputs. Example use below
fn(1) % = 1
fn(1,5,3) % = 35 = (1^2+5^2+3^2)
fn(1,2,3,4,5,6) % = 91 = (1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2)

Duplicating functions in Julia

I need to overwrite a function based on its previous definition, and this leads to a stackoverflow error.
I have tried with deepcopy(f), but it just returns a reference to f, so this doesn't work.
What I need to be able to do over and over is:
Old(x) = pdf(Uniform(),x)
New(x) = updating_function(Old, Y1)
Old(x) = deepcopy(New(x))
New(x) = updating_function(Old, Y2)
[...]
EDIT:
My overall goal is to have a function that takes a prior distribution and spits out a posterior with an unusual signal structure due to my application.
A simple running example of this would be
Old_pdf(x)= pdf(Uniform(),x)
Old_mean=0.5
function BU(d,low)
value, tol = quadgk(Old_pdf, Old_λ, 1)
truncated(λ)=d(λ)/value
end
Newpdf=BU(Old_pdf,Old_mean)
Old_mean, tol= quadgk(x -> Newpdf(x)*x, Old_mean, 1)
Old_pdf=BU(Old_pdf,Old_mean)
I know that this example could be addressed with functions from the Distributions package. It's not the case for my application.
I have found this question and read the documentation of the IRTools package, but I am unable to make this work. In particular when I try
Old(x) = pdf(Uniform(),x)
New(x) = updating_function(Old, Y1)
const Old_ir= IRTools.Inner.code_ir(New, Tuple{Int})
Old(x) = IRTools.func(Old_ir)
I obtain an object that doesn't behave like a function, hence generates methods error in the rest of the code. I made several attempts at this, and it is entirely possible that I am missing something trivial.
Y1 = 5.0
Y2 = 7.0
updating_function(f1,c) = x -> 2.0 * f1(x) + c
Old = x->sqrt(x)
New = updating_function(Old, Y1)
Old = New
New = updating_function(Old, Y2)
I think you just need anonymous functions:
function BU(f, λ, y)
# I guess here you would use the observations `y` in some way?
z, _ = quadgk(f, λ, 1)
return λ -> f(λ) / z
end
mean(f, λ) = quadgk(x -> f(x) * x, λ, 1)[1]
original_pdf(x) = pdf(Uniform(), x)
f = original_pdf
λ = 0.5
for y in Y
f = BU(f, λ, y)
λ = mean(f, λ)
end
Now I tried very hard, and I think I understand what you're doing, but the example you gave wasn't very clear. Consider this conceptual.
Such things make nice folds, by the way.

Sympy: Substitution with functions

I have a function f:
f = Function('f')(x,y).
The output of my program is a large polynomial with terms XYf, Xf, Yf for variables X and Y. I would like to define the substitution such that
X f(x,y) = f(x+1,y)
Y f(x,y) = f(x,y+1)
Similarly, XY f(x,y) = f(x+1,y+1).
I have used the following code to define the operation of X and Y.
poly = poly.subs(X*f, f.subs(x,x+1))
poly = poly.subs(Y*f, f.subs(y,y+1))
Though this works with terms of Xf and Yf, it does not work with terms of XYf. XYf gives the output as Yf(x+1,y) instead of f(x+1,y+1).
How do I force Y to act on the "new" f?
XYf gives Yf(x+1, y) because it matches Xf and that's the first substitution you do. To replace all three in the way that you want, you should do them in an order such that you don't match later instances, like
poly = poly.subs(X*Y*f, f.subs(x,x+1).subs(y, y + 1))
poly = poly.subs(X*f, f.subs(x,x+1))
poly = poly.subs(Y*f, f.subs(y,y+1))
That way, you replace all X*Y*f(x, y) first, so when you replace X*f(x, y) and Y*f(x, y) it won't replace X*Y*f(x, y) (because they will already be replaced).
As a side note, in terms of code clarity, it's going to be simpler if you just define
f = Function('f')
and then explicitly write f(x, y), f(x + 1, y), and so on (rather than letting f = f(x, y) and using subs to create f(x + 1, y) and so on).

How should I rewrite this code to not use feval?

I recently finished a homework set in my Applied Numerical Methods class and did alright on it. However, my professor made a note to say I shouldn't use the feval() function because it's outdated.
I'm just wondering what I should use instead.
Here is the code in question
%% function file
function E=euler(f,a,b,ya,h)
t=a:h:b;
y(1)=ya;
for i=1:length(t)-1
y(i+1) = y(i) + h*(feval(f,t(i),y(i)));
end
t = t';
y = y';
E=t;
plot(t,y)
xlabel('t')
ylabel('y')
end
%% script file
f = #(y,t) (1-20*t*y)/(t^2); %solved for dy/dt
x = 2:0.0001:10;
exact = 1./(19.*x) - 524288./(19.*x.^20);
figure(1)
plot(exact);
a = 2;
b = 10;
ya = 1;
h = 0.01;
figure(2)
y1=euler(f, a, b, ya, h);
h = 0.001;
figure(3)
y2=euler(f, a, b, ya, h);
h = 0.0001;
figure(4)
y3=euler(f, a, b, ya, h);
How could I write this code to still properly evaluate the Euler function without using the feval function.
For example, you can see that
[V,D] = feval('eig',A)
[V,D] = eig(A)
Are equivalent.

Passing additional arguments through function handle in Matlab

I have a function to optimize, say Function, in Matlab. This function depends on variables (say x) over which I want to optimize and one parameter (say, Q) which does not need to be optimized.Hence, the function Function(x,Q). In other words, I have an array of values for Q and want to find optimal x values for each Q. However, I cannot find a way how to pass those Q values when using function handle #Function in optimization function.
So, my question is how to pass those Q values when using function handle in optimization functions, for example fmincon(#Function,x0,A,b)?
Try using anonymous function:
x = cell( 1, numel(Q) );
for qi = 1:numel( Q )
x{qi} = fmincon( #(x) Function(x, Q(qi)), A, b );
end
As described in MATLAB documentation, there are actually 3 solutions for this problem:
Anonymous Functions
which is described in the Shai's answer of this post.
Nested Functions:
in this approach the outer function accepts all arguments, and the inner function only accepts parameters that optimization takes place on them.
this is an example taken from MATLAB documentation:
function [x,fval] = runnested(a,b,c,x0)
[x,fval] = fminunc(#nestedfun,x0);
% Nested function that computes the objective function
function y = nestedfun(x)
y = (a - b*x(1)^2 + x(1)^4/3)*x(1)^2 + x(1)x(2) +...
(-c + cx(2)^2)*x(2)^2;
end
end
Global Variables
in this approach you should define the parameters that are needed in objective function as global in workspace, and use them in objective function with declaring them as global.
here is an example again from MATLAB documentation:
Defining objective function:
function y = globalfun(x)
global a b c
y = (a - b*x(1)^2 + x(1)^4/3)*x(1)^2 + x(1)x(2) + ...
(-c + cx(2)^2)*x(2)^2;
end
Optimization:
global a b c;
a = 4; b = 2.1; c = 4; % Assign parameter values
x0 = [0.5,0.5];
[x,fval] = fminunc(#globalfun,x0)
You may be able to do the following:
x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options,Q)
which will pass Q along to fun(x,Q)!