MATLAB differentiation when the derivative of a function is numerically known - matlab

I want to differentiate the following function wrt in MATLAB:
T(e(x(t),t)⁄p(t))
My problem is that I know the derivatives of x numerically (I am inside a kind of odefun).
I want to use diff to make my code generalizeable for high order derivatives,but the derivatives of x are now constant. I would also like all this to be in an anonymous function where I can make the differentiation and substitute accordingly the time and the derivative of x needed,so that I don't have to write multiple functions for every state of my system.
My code is as follows:
syms q x star;
qd=symfun(90*pi/180+30*pi/180*cos(q),[q]);
p=symfun(79*pi/180*exp(-1.25*q)+pi/180,[q]);
T=log(-(1+star)/star);
e=symfun(x-qd,[x,q]);
and I want to write for example a function in the form
#(t,y)(d^2⁄dt^2 T(e(x(t),t)⁄p(t))+d⁄dt T(e(x(t),t)⁄p(t))+T(e(x(t),t)⁄p(t)))

I am not sure of the implementation details but in general this is one approach that you could take. It involves two steps.
in the T(.) function replace x with exp(t) this way when you do the differentiation exp(t) always stays there for the higher order derivatives to be taken and the outer functions will be differentiated with respect to x at the same time. After you do diff you should receive an expression that contains exp(t) (not tested so hopefully it is the case). At this point exp(t) is your time derivative of x. Now you only need to evaluate this expression in t. When doing so you need to replace exp(t) by the derivative of x. I do not know if this can be done, if not then perhaps using y instead of exp(t) with the constraint y=exp(t) would do it but you need to figure the correct implementation out yourself.
Here you need to substitute the derivative of x at the right t. If you do not have the value at the particular point t then do what I suggested in the comment. Pre-calculate it beforehand in many points and interpolate in this step.
This approach relies on swapping x(t) with exp(t) if that does not work then I would do what I suggested in the comment. Approximate x(t) by a known function and use that instead of x in your code.

Related

Numerical gradient of a Matlab function evaluated at a certain point

I have a Matlab function G(x,y,z). At each given (x,y,z), G(x,y,z) is a scalar. x=(x1,x2,...,xK) is a Kx1 vector.
Let us fix y,z at some given values. I would like your help to understand how to compute the derivative of G with respect to xk evaluated at a certain x.
For example, suppose K=3
function f= G(x1,x2,x3,y,z)
f=3*x1*sin(z)*cos(y)+3*x2*sin(z)*cos(y)+3*x3*sin(z)*cos(y);
end
How do I compute the derivative of G(x1,x2,x3,4,3) wrto x2 and then evaluate it at x=(1,2,6)?
You're looking for the partial derivative of dG/dx2
So the first thing would be getting rid of your fixed variables
G2 = #(x2) G(1,x2,6,4,3);
The numerical derivatives are finite differences, you need to choose an step h for your finite difference, and an appropriate method
The simplest one is
(G2(x2+h)-G2(x2))/h
You can make h as small as your numeric precision allows you to. At the limit h -> 0 the finite difference is the partial derivative

Dirac probability measure in Matlab

I want to implement densities of probability measures in Matlab. For that I define density as a function handle such that the integral of some function f (given as a function handle) on the interval [a,b] can be computed by
syms x
int(f(x)*density(x),x,a,b)
When it comes to the Dirac measure the problem is that
int(dirac(x),x,0,b)
delivers the value 1/2 instead of 1 for all b>0. However if I type
int(dirac(x),x,a,b)
where a<0 and b>0 the returned value is 1 as it should be. For this reason multiplying by 2 will not suffice as I want my density to be valid for all intervals [a,b]. I also dont want to distinct cases before integrating so that the code remains valid for a large class of densities.
Does someone know how I can implement the Dirac probability measure (as defined here) in Matlab?
There's no unique, accepted definition for int(delta, 0, b). The problem here isn't that you're getting the "wrong" answer as that you want to impose a different convention somehow on what the delta function is than what was provided by Matlab. (Their choice is defensible but not unique.) If you evaluate this in Wolfram Alpha, for example, it will give you theta(0) - which is not defined as anything in particular. Here theta is the Heaviside function. If you want to impose your own convention, implement your own delta function.
EDIT
I see you wrote a comment on the question, while I was writing this answer, so.... Keep in mind that the Dirac measure or Dirac delta function is not a function at all. The problem you're having, along with what's described below, all relate to trying to give a functional form to something that is inherently not a function. What you are doing is not well-defined in the framework that you have in Matlab.
END OF EDIT
To put the point about conventions in context, the delta function can be defined by different properties. One is that int(delta(x) f(x), a, b) = f(0) when a < 0 < b. This doesn't tell you anything about the integral that you want. Another, which probably leads to an answer as you're getting from Matlab, is to define it as a limit. One (but not the only choice) is the limit of the zero-mean Gaussian as the variance goes to 0.
If you want to use a convention int(delta(x) f(x), a, b) = f(0) when a <= 0 < b, that probably won't get you in much trouble, but just keep in mind that it's a convention you've chosen more than a "right" or
"wrong" answer relative to what you got from Matlab.
As related note, there is a similar choice to be made on the step function (Heaviside function) at x=0. There are conventions in which is is (a) undefined, (b) -1, (c) +1, and (d) 1/2. None is "wrong." This probably corresponds roughly to the choice on the Dirac function since the Heaviside is (roughly) the integral of the Dirac.

How to find the intersections of two functions in MATLAB?

Lets say, I have a function 'x' and a function '2sin(x)'
How do I output the intersects, i.e. the roots in MATLAB? I can easily plot the two functions and find them that way but surely there must exist an absolute way of doing this.
If you have two analytical (by which I mean symbolic) functions, you can define their difference and use fzero to find a zero, i.e. the root:
f = #(x) x; %defines a function f(x)
g = #(x) 2*sin(x); %defines a function g(x)
%solve f==g
xroot = fzero(#(x)f(x)-g(x),0.5); %starts search from x==0.5
For tricky functions you might have to set a good starting point, and it will only find one solution even if there are multiple ones.
The constructs seen above #(x) something-with-x are called anonymous functions, and they can be extended to multivariate cases as well, like #(x,y) 3*x.*y+c assuming that c is a variable that has been assigned a value earlier.
When writing the comments, I thought that
syms x; solve(x==2*sin(x))
would return the expected result. At least in Matlab 2013b solve fails to find a analytic solution for this problem, falling back to a numeric solver only returning one solution, 0.
An alternative is
s = feval(symengine,'numeric::solve',2*sin(x)==x,x,'AllRealRoots')
which is taken from this answer to a similar question. Besides using AllRealRoots you could use a numeric solver, manually setting starting points which roughly match the values you have read from the graph. This wa you get precise results:
[fzero(#(x)f(x)-g(x),-2),fzero(#(x)f(x)-g(x),0),fzero(#(x)f(x)-g(x),2)]
For a higher precision you could switch from fzero to vpasolve, but fzero is probably sufficient and faster.

MATLAB complicated integration

I have an integration function which does not have indefinite integral expression.
Specifically, the function is f(y)=h(y)+integral(#(x) exp(-x-1/x),0,y) where h(y) is a simple function.
Matlab numerically computes f(y) well, but I want to compute the following function.
g(w)=w*integral(1-f(y).^(1/w),0,inf) where w is a real number in [0,1].
The problem for computing g(w) is handling f(y).^(1/w) numerically.
How can I calculate g(w) with MATLAB? Is it impossible?
Expressions containing e^(-1/x) are generally difficult to compute near x = 0. Actually, I am surprised that Matlab computes f(y) well in the first place. I'd suggest trying to compute g(w)=w*integral(1-f(y).^(1/w),epsilon,inf) for epsilon greater than zero, then gradually decreasing epsilon toward 0 to check if you can get numerical convergence at all. Convergence is certainly not guaranteed!
You can calculate g(w) using the functions you have, but you need to add the (ArrayValued,true) name-value pair.
The option allows you to specify a vector-valued w and allows the nested integral call to receive a vector of y values, which is how integral naturally works.
f = #(y) h(y)+integral(#(x) exp(-x-1/x),0,y,'ArrayValued',true);
g = #(w) w .* integral(1-f(y).^(1./w),0,Inf,'ArrayValued',true);
At least, that works on my R2014b installation.
Note: While h(y) may be simple, if it's integral over the positive real line does not converge, g(w) will more than likely not converge (I don't think I need to qualify that, but I'll hedge my bets).

What function does Microsoft Solver Foundation's InteriorPointSolver minimize?

I am attempting to use InteriorPointSolver to solve a standard Quadratic Programming problem with linear constraints (per the definition that can be found here). My problem has no linear term (the "c" vector in the definition). I am setting up the "Q" matrix by using SetCoefficient(Int32, Rational, Int32, Int32) across all my variables (passing the "goal" row as the vidRow). Am I correct in assuming that the InteriorPointSolver is minimizing the objective function as defined in the standard definition of the quadratic programming problem?
I ask this because when I calculate x^T * Q * x myself (using the optimal solution for x that I get from the solver), I get a value that is substantially different than what the solver claims the optimal objective function value is (via Statistics.Primal or GetValue(goal)). The only time my calculation and the solver's optimal value agree is when I use an identity matrix for Q. I am guessing that I am setting something up wrong or am not understanding exactly what function is being minimized.
I have consulted all the documentation I can find and cannot find a good explanation of exactly what function the interior point solver is minimizing. Can anyone guide me in the right direction?
As it turns out,
SetCoefficient(goal, 2.0, x, y)
Has exactly the same effect as
SetCoefficient(goal, 2.0, y, x)
The effect of both calls is to set the coefficient of the x*y term in your objective function, and the second call simply overwrites the coefficient that you set in the first call. The solver does not treat the xy term as distinct from the yx term, and does not add the coefficients (as I had expected). So, if your goal is to have a 4xy term in your objective function, you must make the following call:
SetCoefficient(goal, 4.0, x, y)
instead of the two calls listed above.