How I do evaluate a function handle in other function handle?(matlab) - algorithm

function [v] = f_dora(f,x0,y0,n)
p_y=#(f,x,y) (f(x,y+0.0001) - f(x,y-0.0001))/(2*0.0001);
p_x=#(f,x,y) (f(x+0.0001,y) - f(x-0.0001,y))/(2*0.0001);
for i=1:n
g=#(x,y) f(x,y)*p_y(f,x,y) + p_x(f,x,y)
f=#(x,y) g(x,y)
end
v=f(x0,y0);
end
This function has a input f, like (f=#((x,y) y -x^2 +1), and want to has as output $f^n(x,y)$ (the nth derivative of f, where y depends of x)
The steps that I follow to solve this problem are:
First, I define the function p_y and p_x that is the partial derivate aproximation of f.
And, I define the function g, which is the (p_x + p_y*f(x,y))(this is the form of the derivate f)
Finally, I want to evaluate n times the function g_k in the same function, something like this:
g_1=#(x,y) f(x,y)*p_y(f,x,y) + p_x(f,x,y);
g_2=#(x,y) g_1(x,y)*p_y(g_1,x,y) + p_x(g_1,x,y);
.
.
.
g_n=#(x,y) g_(n-1)(x,y)*p_y(g_(n-1),x,y) + p_x(g_(n-1),x,y);
g_n(x,y)
or
Algorithm
But, when I use the first code I have incorrect results for n>=3.
A example to try the code, is using f_dora(#((x,y) y -x^2 +1,0,0.5,n), and for n=1, the result that would be correct is 1.5. For n=2,the result that would be correct is -0.5, for n=3. the result that would be correct is -0.5....
Someone could help me by seeing what the errors are in my code?, or does anyone know any better way to calculate partial derivatives without using the symbolic?

Related

Julia JuMP array variable constraint

I am trying to model a non-linear problem involving vector rotation using JuMP in Julia. I need a constraint, which looks something like v[1:3] == rotate(v) If I write it like this, it does not work, since "Nonlinear expressions may contain only scalar expressions". How can I work around this?
I could say something like v[1] == rotate(v)[1] and same for v[2] and v[3], but then I would have to compute rotate(v) three times as often. I could also try to split the rotate function into three functions which compute one element each, but the actual constraint is a bit more complicated than a simple rotation, so this could prove to be tricky.
Are there any other ways to do this? Maybe to have something like an auxiliary variable which can be computed as a vector and then in the constraint only compare the elements of the two vectors (essentialy the first approach, but without computing the function three times)?
See here for a suggested work-around:
https://discourse.julialang.org/t/how-to-set-up-nlconstraints-from-multi-output-user-defined-function/42309/5?u=odow
using JuMP
using Ipopt
function myfun(x)
return sum(xi for xi in x), sum(xi^2 for xi in x)
end
function memoized()
cache = Dict{UInt, Any}()
fi = (i, x) -> begin
h = hash((x, typeof(x)))
if !haskey(cache, h)
cache[h] = myfun(x)
end
return cache[h][i]::Real
end
return (x...) -> fi(1, x), (x...) -> fi(2, x)
end
model = Model(Ipopt.Optimizer)
f1, f2 = memoized()
register(model, :f1, 3, f1; autodiff = true)
register(model, :f2, 3, f2; autodiff = true)
#variable(model, x[1:3] >= 0, start = 0.1)
#NLconstraint(model, f1(x...) <= 2)
#NLconstraint(model, f2(x...) <= 1)
#objective(model, Max, sum(x))
optimize!(model)

Integral changes variable subscripts

I have been away from Mathematica for quite a while and am trying to fix some old notebooks from v4 that are no longer working under v11. I'm also a tad rusty.
I am attempting to use functional minimization to fit a polynomial of variable degree to an arbitrary function (F) given a starting guess (ao) and domain of interest (d). Note that while F is arbitrary, its nature is such that the integral of the product of F and a polynomial (or F^2) can always be evaluated algebraically.
For the sake of example, I'll use the following inputs:
ao = { 1, 2, 3, 4 }
d = { -1, 1 }
F = Sin[x]
To do so, I create an array of 'indexed' variables
polyCoeff = Array[a,Length[a],0]
Result: polycoeff = {a[0], a[1], a[2], a[3]}
I then create the polynomial itself using the following
genPoly[{},x_] := 0
genPoly[a_List,x_] := First[a] + x genPoly[Rest[a],x]
poly = genPoly[polyCoeff,x]
Result: poly = a[0] + x (a[1] + x (a[2] + x a[3]))
I then define my objective function as the integral of the square of the error of the difference between this poly and the function I am attempting to fit:
Q = Integrate[ (poly - F[x])^2, {x, d[[1]],d[[2]]} ]
result: Q = 0.545351 - 2. a[0.]^2 + 0.66667 a[1.]^2 + .....
And this is where things break down. poly looks just as I expected: a polynomial in x with coefficients that look like a[0], a[1], a[2], ... But, Q is not exactly what I expected. I expected and got a new polynomial. But not the coefficients contained a[0.], a[1.], a[2.], ...
The next step is to create the initial guess for FindMinimum
init = Transpose[{polyCoeff,ao}]
Result: {{a[0],1},{a[1],2},{a[3],3},{a[4],4}}
This looks fine.
But when I make the call to FindMinimum, I get an error because the coefficients passed in the objective (a[0.],a[1.],...) do not match those passed in the initial guess (a[0],a[1],...).
S = FindMinimum[Q,init]
So I think my question is how do I keep Integrate from changing the arguments to my coefficients? But, I am open to other approaches as well. Keep in mind though that this is "legacy" work that I really don't want to have to completely revamp.
Thanks much for any/all help.

Optimizing computational cost on a task involving a multi-nested loop

I am just a beginner of programming, and sorry in advance for bothering you by a (presumably) basic question.
I would like to perform the following task:
(I apologize for inconvenience; I don't know how to input a TeX-y formula in Stack Overflow ). I am primarily considering an implementation on MATLAB or Scilab, but language does not matter so much.
The most naive approach to perform this, I think, is to form an n-nested for loop, that is (the case n=2 on MATLAB is shown for example),
n=2;
x=[x1,x2];
for u=0:1
y(1)=u;
if x(1)>0 then
y(1)=1;
end
for v=0:1
y(2)=v;
if x(2)>0 then
y(2)=1;
end
z=Function(y);
end
end
However, this implementation is too laborious for large n, and more importantly, it causes 2^n-2^k abundant evaluations of the function, where k is a number of negative elements in x. Also, naively forming a k-nested for loop with knowledge of which element in x is negative, e.g.
n=2;
x=[-1,2];
y=[1,1];
for u=0:1
y(1)=u;
z=Function(y);
end
doesn't seem to be a good way; if we want to perform the task for different x, we have to rewrite a code.
I would be grateful if you provide an idea to implement a code such that (a) evaluates the function only 2^k times (possible minimum number of evaluations) and (b) we don't have to rewrite a code even if we change x.
You can evaluate Function on y in Ax easily using recursion
function eval(Function, x, y, i, n) {
if(i == n) {
// break condition, evaluate Function
Function(y);
} else {
// always evaluate y(i) == 1
y(i) = 1;
eval(Function, x, y, i + 1, n);
// eval y(i) == 0 only if x(i) <= 0
if(x(i) <= 0) {
y(i) = 0;
eval(Function, x, y, i + 1, n);
}
}
}
Turning that into efficient Matlab code is another problem.
As you've stated the number of evaluations is 2^k. Let's sort x so that only the last k elements are non-positive. To evaluate Function index y using the reverse of the permutation of the sort of x: Function(y(perm)). Even better the same method allows us to build Ax directly using dec2bin:
// every column of the resulting matrix is a member of Ax: y_i = Ax(:,i)
function Ax = getAx(x)
n = length(x);
// find the k indices of non-positives in x
is = find(x <= 0);
k = length(is);
// construct Y (last k rows are all possible combinations of [0 1])
Y = [ones(n - k, 2 ^ k); (dec2bin(0:2^k-1)' - '0')];
// re-order the rows in Y to get Ax according to the permutation is (inverse is)
perm([setdiff(1:n, is) is]) = 1:n;
Ax = Y(perm, :);
end
Now rewrite Function to accept a matrix or iterate over the columns in Ax = getAx(x); to evaluate all Function(y).

Mathematica Order of an Equation

Is there a way to obtain the order of an ODE in mathematica.
For example, if i have y''+5y i want mathematica return 2 (beacuse it's a 2nd order equation). So, is it possible what i'm asking?
here is a way to extract the value automatically:
ode = y'' + y' + y == 0 ;
Max[Cases[ ode , Derivative[n_][y] :> n , Infinity]]
2
note this just finds the largest derivative in the expression, it doesn't verify if the expression is actually an ode..

Algorithm for functions permutating integers

I want to write some functions as follows
y = f(x) and another function,
x = g(y) that acts as a reversible, where
y = f(g(y)) and where x and y are permutated integers.
For very simple example in the range of integers in 0 to 10 it would look like this:
0->1
1->2
2->3
...
9->10
10->0
but this is the simplest method by adding 1 and reversing by subtracting 1.
I want to have a more sofisticated algorithm that can do the following,
234927773->4299
34->33928830
850033->23234243423
but the reverse can be obtained by conversion
The solution could be obtained with a huge table storing pairs of unique integers but this will not be correct. This must be a function.
You could just XOR.
y = x XOR p
x = y XOR p
Though not my area of expertise, I think that cryptography should provide some valuable answers to your question.
If the domain of your permutation is a power of 2, you can use any block cipher: 'f' is encryption with a specific key, and 'g' is decryption with the same key. If your domain is not a power of 2, you can probably still use a block cipher: see this article.
You could use polynomial interpolation methods to interpolate a function one way, then do reverse interpolation to find the inverse function.
Here is some example code in MATLAB:
function [a] = Coef(x, y)
n = length(x);
a = y;
for j = 2:n
for i = n:-1:j
a(i) = (a(i) - a(i-1)) / (x(i) - x(i-j+1));
end
end
end
function [val] = Eval(x, a, t)
n = length(x);
val = a(n);
for i = n-1:-1:1
val = a(i) + val*(t-x(i));
end
end
It builds a Divided Difference table and evaluates a function based on Newtons Interpolation.
Then if your sets of points are x, and y (as vectors of the same length, where x(i) matches to y(i), your forward interpolation function at value n would be Eval(x, Coef(x, y), n) and the reverse interpolation function would be Eval(y, Coef(y, x), n).
Depending on your language, there are probably much cleaner ways to do this, but this gets down and dirty with the maths.
Here is an excerpt from the Text Book which is used in my Numerical Methods class: Google Book Link

Resources