How to set up a large set of first order non-linear differential equations in Matlab? - matlab

I am relatively new to writing my own code for Matlab though I have used the program a decent amount. Right now I am attempting to code a series of first order non-linear differential equations. They are all in one of two forms like the equations here:
Eventually I will need a set of 30 differential equations.
What I was hoping to do was create a function that could make the differential equation for each component of a certain form, combine them into a single system (essentially a matrix with 1 column and a row for each component), and then solve using a Matlab solver like ODE45, the dsolve function, or something like that to solve the system.
I have not yet found a way to make a function set up this large of a system that works with either dsolve or ODE45. The results always either gave me an empty sym or an error that the initial conditions were not compatible with the system or some other error. So what I am wondering is if there is another way to go about setting up a system that is this large and has nonlinear differential equations.
I do not want someone else's code; I just want an idea for how to go about setting this up in Matlab because nothing I have tried has worked so far.

Related

How to solve this system of differential equations in matlab?

My task is to model a certain physical problem and use matlab to solve it's differential equations. I made the model but it seems far more complex than what I've learned so far so I have no idea how to solve this.
The black color means it's a constant
I assume that by "solve" you seek a closed form solution of the form x(t) = ..., z(t) = ... Unforunately, it's very likely you cannot solve this system of differential equations. Only very specific canonical systems actually have a closed-form solution, and they are the most simple (few terms and dependent variables). See Wikipedia's entry for Ordinary Differential Equations, in particular the section Summary of exact solutions.
Nevertheless, the procedure for attempting to solve with Matlab's Symbolic Math Toolbox is described here.
If instead you were asking for numerical integration, then I will give you some pointers, but you must carry out the math:
Convert the second order system to a first order system by using a substitution w(t) = dx/dt, allowing you to replace the d2x/dt2 term by dw/dt. Example here.
Read the documentation for ode15i and implement your transformed model as an implicit differential equation system.
N.B. You must supply numerical values for your constants.

Explain Matlab ode45 output. Is ode45 an iterative algorithm?

I tried to use ode45 to solve an equation, and get output like the following. I get the idea it is trying to estimate using nearby points (as explained here https://www.mathworks.com/videos/solving-odes-in-matlab-6-ode45-117537.html). By my understanding, it should solve the equation in one round of computation? but the output looks like ode45 is an iterative algorithm (so that it generates output that repeat the '... steps ... failed attempt ... function evaluations' over and over again)? If it is iterative, could you help give some detail or references? Thanks!
ode45 is an iterative adaptive ODE solver. That is, it uses a 5th order (FSAL) method to propose the an update using some stepsize h. Then it does the same again, but now with a 4th order method, then it compared those two updates to one another, if the difference is less than some local tolerance, it accepts the proposed update. If the difference is larger than some local tolerance, the update is rejected and the stepsize is lowered (in some smart way).
To reduce the cost of using both a 4th and 5th order method, those two methods uses (roughly) the same function evaluations.
As for your output, it is, as also noted by #LutzL, not the standard output, which might point to an error in your code.

Fit data with a numerical ode solution (on Matlab)

I am looking for a way to fit my experimental data by a theoretical model which is described by a non-linear differential equation.
Unfortunately this latter can only be solved numerically (by solving this second degree, non-linear differential equation).
I manage to solve the differential equation for a set of parameters using the ode45 Matlab solver but now I want to find the proper fit parameters of the model. Also, I may have to mention that my ode45 is initiated at z=zmax (max being large so I can assume it is infinity) by y(zmax)=y0 and yprime(zmax)=yprime0 and I solve backward (from zmax to z=0).
I am quite new to this kind of numerical problems, are there classical ways to solve such problems?
Does anyone knows if there is a Matlab procedure which would help me solve this? On which principles is it based/constructed? (if possible I'd like to know the theoretical trick to solve this problem in a smart way, not by trying all the possible sets of parameters which would be very time consuming (I have 5 fit parameters!).
Thank you for your precious help!
You have facy methods in the Optimization Toolbox. In case you don't have access to it, you could do it manually by:
Selecting a cost function between the experimental and model data. For example, mean-squared-error.
Doing heuristic optimization of the cost function. For example, Nelder-Mead method.

Optimization in NMPC of second order pendulum model

Hopefully, I will be able to explain my question well.
I am working on Nonlinear model predictive control implementation.
I have got 3 files:
1). a simulink slx file which is basically a nonlinear pendulum model.
2). A function file, to get the cost function from the simulink model.
3). MPC code.
code snippet of cost function
**simOut=sim('NonlinearPendulum','StopTime', num2str(Np*Ts));**
%Linearly interpolates X to obtain sampled output states at time instants.
T=simOut.get('Tsim');
X=simOut.get('xsim');
xt=interp1(T,X,linspace(0,Np*Ts,Np+1))';
U=U(1:Nu);
%Quadratic cost function
R=0.01;
J=sum(sum((xt-repmat(r,[1 Np+1])).*(xt-repmat(r,[1 Np+1]))))+R*(U-ur)*...
(U-ur)';
Now I take this cost function and optimize it using fmincon to generate a sequence of inputs to be applied to the model, using my MPC code.
A code snippet of my MPC code.
%Constraints -1<=u(t)<=1;
Acons=[eye(Nu,Nu);-eye(Nu,Nu)];
Bcons=[ones(Nu,1);ones(Nu,1)];
options = optimoptions(#fmincon,'Algorithm','active-set','MaxIter',100);
warning off
for a1=1:nf
X=[]; %Prediction output
T=[]; %Prediction time
Xsam=[];
Tsam=[];
%Nonlinear MPC controller
Ubreak=linspace(0,(Np-1)*Ts,Np); %Break points for 1D lookup, used to avoid
% several calls/compilations of simulink model in fmincon.
**J=#(v) pendulumCostFunction(v,x0,ur,r(:,a1),Np,Nu,Ts);**
U=fmincon(J,U0,Acons,Bcons,[],[],[],[],[],options);
%U=fmincon(J,U0,Acons,Bcons);
U0=U;
UUsam=[UUsam;U(1)];%Apply only the first selected input
%Apply the selected input to plant.
Ubreak=[0 Ts]; %Break points for 1D lookup
U=[UUsam(end) UUsam(end)];
**simOut=sim('NonlinearPendulum','StopTime', num2str(Ts));**
In both the codes, I have marked the times we call our simulink model. Now, issue is that to run this whole simulation for just 5 seconds it takes around 7-8 minutes on my windows machine, MATLAB R2014B.
Is there a way to optimize this? As, I am planning to extend this algorithm to 9th order system unlike 2nd order pendulum model.
If, anyone has suggestion on using simulink coder to generate C code:
I have tried that, and the problem I face is that I don't know what to do with the several files generated. Please be as detailed as possible.
From the code snippets, it appears that you are solving a linear time invariant model with a quadratic objective. Here is some MATLAB (and Python) code for an overhead crane pendulum and inverted pendulum, both with state space linear models and quadratic objectives.
One of the ways to make it run faster is to avoid a Simulink interface and a shooting method for solving the MPC. A simultaneous method with orthogonal collocation on finite elements is faster and also enables higher index DAE model forms if you'd like to use a nonlinear model.

Solving a non-polynomial equation numerically

I've got a problem with my equation that I try to solve numerically using both MATLAB and Symbolic Toolbox. I'm after several source pages of MATLAB help, picked up a few tricks and tried most of them, still without satisfying result.
My goal is to solve set of three non-polynomial equations with q1, q2 and q3 angles. Those variables represent joint angles in my industrial manipulator and what I'm trying to achieve is to solve inverse kinematics of this model. My set of equations looks like this: http://imgur.com/bU6XjNP
I'm solving it with
numeric::solve([z1,z2,z3], [q1=x1..x2,q2=x3..x4,q3=x5..x6], MultiSolutions)
Changing the xn constant according to my needs. Yet I still get some odd results, the q1 var is off by approximately 0.1 rad, q2 and q3 being off by ~0.01 rad. I don't have much experience with numeric solve, so I just need information, should it supposed to look like that?
And, if not, what valid option do you suggest I should take next? Maybe transforming this equation to polynomial, maybe using a different toolbox?
Or, if trying to do this in Matlab, how can you limit your solutions when using solve()? I'm thinking of an equivalent to Symbolic Toolbox's assume() and assumeAlso.
I would be grateful for your help.
The numerical solution of a system of nonlinear equations is generally taken as an iterative minimization process involving the minimization (i.e., finding the global minimum) of the norm of the difference of left and right hand sides of the equations. For example fsolve essentially uses Newton iterations. Those methods perform a "deterministic" optimization: they start from an initial guess and then move in the unknowns space essentially according to the opposite of the gradient until the solution is not found.
You then have two kinds of issues:
Local minima: the stopping rule of the iteration is related to the gradient of the functional. When the gradient becomes small, the iterations are stopped. But the gradient can become small in correspondence to local minima, besides the desired global one. When the initial guess is far from the actual solution, then you are stucked in a false solution.
Ill-conditioning: large variations of the unknowns can be reflected into large variations of the data. So, small numerical errors on data (for example, machine rounding) can lead to large variations of the unknowns.
Due to the above problems, the solution found by your numerical algorithm will be likely to differ (even relevantly) from the actual one.
I recommend that you make a consistency test by choosing a starting guess, for example when using fsolve, very close to the actual solution and verify that your final result is accurate. Then you will discover that, by making the initial guess more far away from the actual solution, your result will be likely to show some (even large) errors. Of course, the entity of the errors depend on the nature of the system of equations. In some lucky cases, those errors could keep also very small.