Partial derivative with Matlab Symbolic Toolbox for Lagrangian equations of motion - matlab

I'm trying to derive Lagrangian equations of motion in Matlab using the symbolic toolbox. This involves partial derivatives of a function and your coordinates, but matlab seems to not accept this.
So I would do this in Matlab:
syms t x(t) % t: time, x(t) position dependent on time
m = sym('m'); % mass, a constant parameter
T = m/2*diff(x,t)^2; % kinetic energy
dTdx = diff(T,x);
ddTdxDotdt = diff( diff(T,diff(x,t)), t);
But as soon as I try to differentiate anything in x (or diff(x,t)), Matlab complains:
Error using mupadmex
Error in MuPAD command: The variable is invalid. [stdlib::diff]
Error in sym/diff (line 44)
R = mupadmex('symobj::diff', S.s, x.s, int2str(n));
Does anyone know the proper way of handling this?

Matlab ought to be able to do this as you have it written, but I think that it doesn't like taking derivatives with respect to a symfun. Type whos in the command window and you'll see that x is listed as a symfun while t is just a sym. The help for diff kind of indicates this limitation. It won't event try to take the derivative of a constant with respect to x(t): diff(1,x) "complains" just the same. Unless newer versions of Matlab fix this (I'm on R2012b) I think you only option may be to come up with a scheme using two instances of x.

Related

Using Matlab to solve a system of ODEs using Euler's method

I have created a function Euler.m to solve a a system of ODEs using Euler's method. I wish to use this function to solve the system of ODEs defined by the anonymous function func=#(t) ([x(t)+4*y(t)-exp(t);x(t)+y(t)+2*exp(t)]) with initial conditions given by y0.
func=#(t) ([x(t)+4*y(t)-exp(t);x(t)+y(t)+2*exp(t)]);
y0=[4;5/4];
y_exact=#(t) [4*exp(3*t)+2*exp(-t)-2*exp(t);2*exp(3*t)-exp(-t)+exp(t)/4]; %exact solution of ODEs
a=0; % such that
b=1; % a<t<b
N=120;
[t,y] = Euler(func,a,b,y0,N)
However, the following error is displayed:
"Error using solution>#(t)([x(t)+4*y(t)-exp(t);x(t)+y(t)+2*exp(t)])
Too many input arguments.
Error in solution (line 7)
[t,y] = Euler(func,a,b,y0,N)".
Why is this error being displayed?
You are pretending that you already know when writing the ODE function func what the solutions x(t),y(t) are. Then you are going to compute solutions approximations for it. This is completely the wrong way around.
The function for the right side is just for a point in phase space, so you need
func=#(t,y) ([y(1)+4*y(2)-exp(t);y(1)+y(2)+2*exp(t)]);
where the input y is a two-component vector.

Minimizing Function with vector valued input in MATLAB

I want to minimize a function like below:
Here, n can be 5,10,50 etc. I want to use Matlab and want to use Gradient Descent and Quasi-Newton Method with BFGS update to solve this problem along with backtracking line search. I am a novice in Matlab. Can anyone help, please? I can find a solution for a similar problem in that link: https://www.mathworks.com/help/optim/ug/unconstrained-nonlinear-optimization-algorithms.html .
But, I really don't know how to create a vector-valued function in Matlab (in my case input x can be an n-dimensional vector).
You will have to make quite a leap to get where you want to be -- may I suggest to go through some basic tutorial first in order to digest basic MATLAB syntax and concepts? Another useful read is the very basic example to unconstrained optimization in the documentation. However, the answer to your question touches only basic syntax, so we can go through it quickly nevertheless.
The absolute minimum to invoke the unconstraint nonlinear optimization algorithms of the Optimization Toolbox is the formulation of an objective function. That function is supposed to return the function value f of your function at any given point x, and in your case it reads
function f = objfun(x)
f = sum(100 * (x(2:end) - x(1:end-1).^2).^2 + (1 - x(1:end-1)).^2);
end
Notice that
we select the indiviual components of the x vector by matrix indexing, and that
the .^ notation effects that the operand is to be squared elementwise.
For simplicity, save this function to a file objfun.m in your current working directory, so that you have it available from the command window.
Now all you have to do is to call the appropriate optimization algorithm, say, the quasi Newton method, from the command window:
n = 10; % Use n variables
options = optimoptions(#fminunc,'Algorithm','quasi-newton'); % Use QM method
x0 = rand(n,1); % Random starting guess
[x,fval,exitflag] = fminunc(#objfun, x0, options); % Solve!
fprintf('Final objval=%.2e, exitflag=%d\n', fval, exitflag);
On my machine I see that the algorithm converges:
Local minimum found.
Optimization completed because the size of the gradient is less than
the default value of the optimality tolerance.
Final objval=5.57e-11, exitflag=1

How to solve an equation with piecewise defined function in Matlab?

I have been working on solving some equation in a more complicated context. However, I want to illustrate my question through the following simple example.
Consider the following two functions:
function y=f1(x)
y=1-x;
end
function y=f2(x)
if x<0
y=0;
else
y=x;
end
end
I want to solve the following equation: f1(x)=f2(x). The code I used is:
syms x;
x=solve(f1(x)-f2(x));
And I got the following error:
??? Error using ==> sym.sym>notimplemented at 2621
Function 'lt' is not implemented for MuPAD symbolic objects.
Error in ==> sym.sym>sym.lt at 812
notimplemented('lt');
Error in ==> f2 at 3
if x<0
I know the error is because x is a symbolic variable and therefore I could not compare x with 0 in the piecewise function f2(x).
Is there a way to fix this and solve the equation?
First, make sure symbolic math is even the appropriate solution method for your problem. In many cases it isn't. Look at fzero and fsolve amongst many others. A symbolic method is only needed if, for example, you want a formula or if you need to ensure precision.
In such an old version of Matlab, you may want to break up your piecewise function into separate continuous functions and solve them separately:
syms x;
s1 = solve(1-x^2,x) % For x >= 0
s2 = solve(1-x,x) % For x < 0
Then you can either manually examine or numerically compare the outputs to determine if any or all of the solutions are valid for the chosen regime – something like this:
s = [s1(double(s1) >= 0);s2(double(s2) < 0)]
You can also take advantage of the heaviside function, which is available in much older versions.
syms x;
f1 = 1-x;
f2 = x*heaviside(x);
s = solve(f1-f2,x)
Yes, the Heaviside function is 0.5 at zero – this gives it the appropriate mathematical properties. You can shift it to compare values other than zero. This is a standard technique.
In Matlab R2012a+, you can take advantage of assumptions in addition to the normal relational operators. To add to #AlexB's comment, you should convert the output of any logical comparison to symbolic before using isAlways:
isAlways(sym(x<0))
In your case, x is obviously not "always" on one side or the other of zero, but you may still find this useful in other cases.
If you want to get deep into Matlab's symbolic math, you can create piecewise functions using MuPAD, which are accessible from Matlab – e.g., see my example here.

How to differentiate a function w.r.t another symbolic function in MATLAB?

Using the code,
syms x(t)
y=x^2
diff(y,t)
diff(y,x)
I get the following error:
2*D(x)(t)*x(t)
Error using sym/diff (line 26)
All arguments, except for the first one, must not be symbolic functions.
Is there a way to tackle this? Thanks for your time.
I dont know much about the Symbolic Math Toolbox, but taking a derivative wrt to a function does not seem to be supported (at least in a direct fashion) for diff.
You can substitute a variable, compute a derivative, and substitute the function back. Like so:
syms z
subs(diff(subs(y,x,z),z),z,x)
ans(t) = 2*x(t)

How to solve complex system of equations using matlab?

I have to analyze 802.11 saturation throughput using matlab, and here is my problem. I'm trying to solve parametric equations below (parameters are m,W,a) using solve function and i get
Warning: Explicit solution could not be found
How could I solve above equations using matlab?
I guess you were trying to find an analytical solution for tau and p using symbolic math. Unless you're really lucky with your parameters (e.g. m=1), there won't be an analytical solution.
If you're interested in numerical values for tau and p, I suggest you manually substitue p in the first equation, and then solve an equation of the form tau-bigFraction=0 using, e.g. fzero.
Here's how you'd use fzero to solve a simple equation kx=exp(-x), with k being a parameter.
k = 5; %# set a value for k
x = fzero(#(x)k*x-exp(-x),0); %# initial guess: x=0