how to store symbolically the derivatives in matlab - matlab

my question relates to the Symbolic Math Toolbox from Matlab. I have the following code:
syms x x_0 u delta sigma_1
mu = sym ('mu(x)');
sigma_u = sym ('sigma(u)');
sigma = sym ('sigma(x)');
f = int (1/sigma_u, u, x_0, x);
df = subs(diff(f,x))
df_2 = subs(diff (f,x,2))
L = subs(mu*df+1/2*sigma^2*df_2)
The result of L is corect
L =
mu(x)/sigma(x) - diff(sigma(x), x)/2
However, for further derivations and for simplicity, I would like to define
sigma_1 = sym('diff(sigma,x)');
or in a similar way such as to get as result for
L =
mu(x)/sigma(x) - sigma_1(x)/2
Basically, I would like to store under a name the symbolic expression diff(sigma(x),x) such that Matlab knows that when it gets this result in a expression, to poste the name sigma_1 (x) instead of diff(sigma(x),x)

Yes it is possible, you can use subs(L, 'diff(sigma(x),x)', 'sigma_1(x)'). Note to make the substitution work, the second input of subs must be exactly like what you want to replace; hence it cannot be 'diff(sigma, x)' which lacks the (x) behind the sigma.
Also note that here is a similar question for which I provided a more complete solution (they asked the question after yours, but I read theirs first).

Related

Implicit differentiation - Second derivative using Matlab

The equation is 4*x^2-2*y^2==9. Using implicit differentiation, I can find that the second derivative of y with respect to x is -9/y^3, which requires a substitution in the final step.
I am trying to duplicate this answer using Matlab's symbolic toolbox. I did find some support for the first derivative here, and was successful finding the first derivative.
clear all
syms x y f
f=4*x^2-2*y^2-9
sol1=-diff(f,x)/diff(f,y)
But I am unable to continue onward to find the second derivative with the final simplification (replacing 4*x^2-2*y^2 with 9).
Can someone show me how to do this in Matlab?
To my knowledge there is no direct way to obtain an implicit second derivative in Matlab. And working with implicit functions in Matlab can be fairly tricky. As a start, your variable y is implicitly a function of x s you should define it as such:
clear all
syms y(x) % defines both x and y
f = 4*x^2-2*y^2-9
Here y(x) is now what is called an arbitrary or abstract symbolic function, i.e., one with no explicit formula. Then take the derivative of f with respect to x:
s1 = diff(f,x)
This returns a function in terms of the implicit derivative of y(x) with respect to x, diff(y(x), x) (in this case diff(y) is shorthand). You can solve this function for diff(y) algebraically with subs and solve:
syms dydx % arbitrary variable
s2 = subs(s1,diff(y),dydx)
s3 = solve(s2,dydx)
This yields the first implicit derivative. You can then take another derivative of this expression to obtain the second implicit derivative as a function of the first:
s4 = diff(s3,x)
Finally, substitute the expression for the first implicit derivative into this and simplify to obtain the final form:
s5 = simplify(subs(s4,diff(y),s3))
This yields (2*(y(x)^2 - 2*x^2))/y(x)^3. And then you can eliminate x using the original expression for f with further substitution and solving:
syms x2
f2 = subs(f,x^2,x2)
x2 = solve(f2,x2)
s6 = subs(s5,x^2,x2)
Finally, you can turn this back into an explicit algebraic expression with a final substitution, if desired:
s7 = subs(s6,y,'y')
This yields your solution of -9/y^3.
This whole process can be written more concisely (but very unclearly) as:
clear all
syms y(x) dydx x2
f = 4*x^2-2*y^2-9;
s1 = solve(subs(diff(f,x),diff(y),dydx),dydx)
s2 = simplify(subs(subs(subs(diff(s1,x),diff(y),s1),x^2,solve(subs(f,x^2,x2),x2)),y,'y'))
There are many other ways to achieve the same result. See also these two tutorials: [1], [2].
It's been almost four years since I asked this question, and got brilliant help from horchler, but I've discovered another method using the chain rule.
syms x y
f=4*x^2-2*y^2-9
dydx=-diff(f,x)/diff(f,y)
d2ydx2=diff(dydx,x)+diff(dydx,y)*dydx
d2ydx2=simplifyFraction(d2ydx2,'Expand',true)
s1=solve(f,x)
subs(d2ydx2,x,s1(2))

Numerical integration of symbolic differentiation - MATLAB

The following is a MATLAB problem.
Suppose I define an function f(x,y).
I want to calculate the partial derivative of f with respect to y, evaluated at a specific value of y, e.g., y=6. Finally, I want to integrate this new function (which is only a function of x) over a range of x.
As an example, this is what I have tried
syms x y;
f = #(x, y) x.*y.^2;
Df = subs(diff(f,y),y,2);
Int = integral(Df , 0 , 1),
but I get the following error.
Error using integral (line 82)
First input argument must be a function
handle.
Can anyone help me in writing this code?
To solve the problem, matlabFunction was required. The solution looks like this:
syms x y
f = #(x, y) x.*y.^2;
Df = matlabFunction(subs(diff(f,y),y,2));
Int = integral(Df , 0 , 1);
Keeping it all symbolic, using sym/int:
syms x y;
f = #(x, y) x.*y.^2;
Df = diff(f,y);
s = int(Df,x,0,1)
which returns y. You can substitute 2 in for y here or earlier as you did in your question. Not that this will give you an exact answer in this case with no floating-point error, as opposed to integral which calculated the integral numerically.
When Googling for functions in Matlab, make sure to pay attention what toolbox they are in and what classes (datatypes) they support for their arguments. In some cases there are overloaded versions with the same name, but in others, you may need to look around for a different method (or devise your own).

Finding unknown limit of integration in MATLAB

I have an equation of the form c = integral of f(t)dt limiting from a constant to a variable (I don't want to show the full equation because it is very long and complex). Is there any way to calculate in MATLAB what the value of that variable is (there are no other variables and the equation is too difficult to solve by hand)?
Assume your limit is from cons to t and g(t) as your function with variable t. Now,
syms t
f(t) = int(g(t),t);
This will give you the indefinite integral. Now f(t) will be
f(t) = f(t)+f(cons);
You have the value of f(t)=c. So just solve the equation
S = solve(f(t)==c,t,'Real',true);
eval(S) will give the answer i think
This is an extremely unclear question - if you do not want to post the full equation, post an example instead
I am assuming this is what you intend: you have an integrand f(x), which you know, and has been integrated to give some constant c which you know, over the limits of x = 0, to x = y, for example, where y may change, and you desire to find y
My advice would be to integrate f(x) manually, fill in the first limit, and subtract that portion from c. Next you could employ some technique such as the Newton-Ralphson method to iteratively search for the root to your equation, which should be in x only
You could use a function handle and the quad function for the integral
myFunc = #(t) exp(t*3); % or whatever
t0 = 0;
t1 = 3;
L = 50;
f = #(b) quad(#(t) myFunc(t,b),t0,t1);
bsolve = fzero(f,2);
Hope it help !

Implementing iterative solution of integral equation in Matlab

We have an equation similar to the Fredholm integral equation of second kind.
To solve this equation we have been given an iterative solution that is guaranteed to converge for our specific equation. Now our only problem consists in implementing this iterative prodedure in MATLAB.
For now, the problematic part of our code looks like this:
function delta = delta(x,a,P,H,E,c,c0,w)
delt = #(x)delta_a(x,a,P,H,E,c0,w);
for i=1:500
delt = #(x)delt(x) - 1/E.*integral(#(xi)((c(1)-c(2)*delt(xi))*ms(xi,x,a,P,H,w)),0,a-0.001);
end
delta=delt;
end
delta_a is a function of x, and represent the initial value of the iteration. ms is a function of x and xi.
As you might see we want delt to depend on both x (before the integral) and xi (inside of the integral) in the iteration. Unfortunately this way of writing the code (with the function handle) does not give us a numerical value, as we wish. We can't either write delt as two different functions, one of x and one of xi, since xi is not defined (until integral defines it). So, how can we make sure that delt depends on xi inside of the integral, and still get a numerical value out of the iteration?
Do any of you have any suggestions to how we might solve this?
Using numerical integration
Explanation of the input parameters: x is a vector of numerical values, all the rest are constants. A problem with my code is that the input parameter x is not being used (I guess this means that x is being treated as a symbol).
It looks like you can do a nesting of anonymous functions in MATLAB:
f =
#(x)2*x
>> ff = #(x) f(f(x))
ff =
#(x)f(f(x))
>> ff(2)
ans =
8
>> f = ff;
>> f(2)
ans =
8
Also it is possible to rebind the pointers to the functions.
Thus, you can set up your iteration like
delta_old = #(x) delta_a(x)
for i=1:500
delta_new = #(x) delta_old(x) - integral(#(xi),delta_old(xi))
delta_old = delta_new
end
plus the inclusion of your parameters...
You may want to consider to solve a discretized version of your problem.
Let K be the matrix which discretizes your Fredholm kernel k(t,s), e.g.
K(i,j) = int_a^b K(x_i, s) l_j(s) ds
where l_j(s) is, for instance, the j-th lagrange interpolant associated to the interpolation nodes (x_i) = x_1,x_2,...,x_n.
Then, solving your Picard iterations is as simple as doing
phi_n+1 = f + K*phi_n
i.e.
for i = 1:N
phi = f + K*phi
end
where phi_n and f are the nodal values of phi and f on the (x_i).

How do I make a function from a symbolic expression in MATLAB?

How can I make a function from a symbolic expression? For example, I have the following:
syms beta
n1,n2,m,aa= Constants
u = sqrt(n2-beta^2);
w = sqrt(beta^2-n1);
a = tan(u)/w+tanh(w)/u;
b = tanh(u)/w;
f = (a+b)*cos(aa*u+m*pi)+a-b*sin(aa*u+m*pi); %# The main expression
If I want to use f in a special program to find its zeroes, how can I convert f to a function? Or, what should I do to find the zeroes of f and such nested expressions?
You have a couple of options...
Option #1: Automatically generate a function
If you have version 4.9 (R2007b+) or later of the Symbolic Toolbox you can convert a symbolic expression to an anonymous function or a function M-file using the matlabFunction function. An example from the documentation:
>> syms x y
>> r = sqrt(x^2 + y^2);
>> ht = matlabFunction(sin(r)/r)
ht =
#(x,y)sin(sqrt(x.^2+y.^2)).*1./sqrt(x.^2+y.^2)
Option #2: Generate a function by hand
Since you've already written a set of symbolic equations, you can simply cut and paste part of that code into a function. Here's what your above example would look like:
function output = f(beta,n1,n2,m,aa)
u = sqrt(n2-beta.^2);
w = sqrt(beta.^2-n1);
a = tan(u)./w+tanh(w)./u;
b = tanh(u)./w;
output = (a+b).*cos(aa.*u+m.*pi)+(a-b).*sin(aa.*u+m.*pi);
end
When calling this function f you have to input the values of beta and the 4 constants and it will return the result of evaluating your main expression.
NOTE: Since you also mentioned wanting to find zeroes of f, you could try using the SOLVE function on your symbolic equation:
zeroValues = solve(f,'beta');
Someone has tagged this question with Matlab so I'll assume that you are concerned with solving the equation with Matlab. If you have a copy of the Matlab Symbolic toolbox you should be able to solve it directly as a previous respondent has suggested.
If not, then I suggest you write a Matlab m-file to evaluate your function f(). The pseudo-code you're already written will translate almost directly into lines of Matlab. As I read it your function f() is a function only of the variable beta since you indicate that n1,n2,m and a are all constants. I suggest that you plot the values of f(beta) for a range of values. The graph will indicate where the 0s of the function are and you can easily code up a bisection or similar algorithm to give you their values to your desired degree of accuracy.
If you broad intention is to have numeric values of certain symbolic expressions you have, for example, you have a larger program that generates symbolic expressions and you want to use these expression for numeric purposes, you can simply evaluate them using 'eval'. If their parameters have numeric values in the workspace, just use eval on your expression. For example,
syms beta
%n1,n2,m,aa= Constants
% values to exemplify
n1 = 1; n2 = 3; m = 1; aa = 5;
u = sqrt(n2-beta^2);
w = sqrt(beta^2-n1);
a = tan(u)/w+tanh(w)/u;
b = tanh(u)/w;
f = (a+b)*cos(aa*u+m*pi)+a-b*sin(aa*u+m*pi); %# The main expression
If beta has a value
beta = 1.5;
eval(beta)
This will calculate the value of f for a particular beta. Using it as a function. This solution will suit you in the scenario of using automatically generated symbolic expressions and will be interesting for fast testing with them. If you are writing a program to find zeros, it will be enough using eval(f) when you have to evaluate the function. When using a Matlab function to find zeros using anonymous function will be better, but you can also wrap the eval(f) inside a m-file.
If you're interested with just the answer for this specific equation, Try Wolfram Alpha, which will give you answers like:
alt text http://www4c.wolframalpha.com/Calculate/MSP/MSP642199013hbefb463a9000051gi6f4heeebfa7f?MSPStoreType=image/gif&s=15
If you want to solve this type of equation programatically, you probably need to use some software packages for symbolic algebra, like SymPy for python.
quoting the official documentation:
>>> from sympy import I, solve
>>> from sympy.abc import x, y
Solve a polynomial equation:
>>> solve(x**4-1, x)
[1, -1, -I, I]
Solve a linear system:
>>> solve((x+5*y-2, -3*x+6*y-15), x, y)
{x: -3, y: 1}