How to solve an overdetermined nonlinear set of equations using Matlab - matlab

I have following Code in Matlab:
function y = myfun(x)
% Set Variables
Svl=1;
B=54.433;
F=4379.250;
T=21.398;
V=53363.500;
% Computing Prefactors with set variables
Zahl1=-B+13.2855-6.10101*Svl;
Zahl2=-F-13938.9+5073.43*Svl;
Zahl3=-V-599882+229920*Svl;
Zahl4=-T-8.2379-0.964978*Svl;
Pl1=2.99983 -0.438557 *Svl;
Pl2=850.573-294663*Svl;
Pl3=31769.1-12055.5*Svl;
Pl4=1.80671 -0.256667 *Svl;
vs1=0.0255558*Svl -0.0498925;
vs2=20.0274 -8.33864*Svl;
vs3=1061.95-415.967*Svl;
vs4=-0.00980451+0.0119915*Svl;
Plvs1=-0.00215169;
Plvs2=-1.20681+0.465007*Svl;
Plvs3=-56.1611+21.7506*Svl;
Plvs4=-0.00162471;
% Equations
y = zeros(4,1);
y(1) = Zahl1+Pl1*x(1)+vs1*x(2)+Plvs1*x(1)*x(2);
y(2) = Zahl2+Pl2*x(1)+vs2*x(2)+Plvs2*x(1)*x(2);
y(3) = Zahl3+Pl3*x(1)+vs3*x(2)+Plvs3*x(1)*x(2);
y(4) = Zahl4+Pl4*x(1)+vs4*x(2)+Plvs4*x(1)*x(2);
I have a set of four nonlinear equations y() and only two unknowns x(1) and x(2). Zahlx, Plx, vsx and Plvsx are known and only prefactors which are computed before in this code.
How do I solve the above set of overdetermined nonlinear equations in Matlab?
I tried it with the least squeres:
x0 = [20,100];
lb = [20,100];
ub = [40,500];
[x,resnorm,res,eflag,output1] = lsqnonlin(#myfun,x0, lb, ub); % Invoke optimizer
x(1)
x(2)
But the result makes no sence.
I get the following result:
Initial point is a local minimum.
Optimization completed because the size of the gradient at the initial point
is less than the default value of the function tolerance.
<stopping criteria details>
%x(1)
ans =
20
%x(2)
ans =
100
But x(1) should be near 40 and x(2) near 500.
He computed only the start point.
Any ideas?
I hope somebody can help me. Thank you very much in advance.

Related

How to solve a coupled nonlinear first order differential equation?

I have a problem in the form of 2 equations and known initial conditions. The equations are:
dx/dt = (-a1*sin(y) + a2 + a3*sin(y-x)) / ((dy/dt)*a4*cos(y-x))
dy/dt = (a1*sin(x) -a5 + a6*x + a7*sin(y-x)) / ((dx/dt)*a8*cos(y-x))
where a1 to a8 are variables.
I am trying to plot x vs t and y vs t on MATLAB, but I am not sure how to solve this numerically or analytically. Any help would be appreciated!!
The ODE of your problem cannot be written as dy/dt=f(t,y) nor M(t,y)dy/dt=f(t,y). That means it is a Differential Algebraic Equation which has to be solved numerically in the form:
f(t, y, dy/dt)=0
In matlab this can be done with the command ode15i.
Therefore, the first step is to write the function in a proper way, in this case, one option is:
function f = cp_ode(t,y,yp,a)
f1 = (-a(1)*sin(y(2))+a(2)+a(3)*sin(y(2)-y(1)))/yp(2)*a(4)*cos(y(2)-y(1)) - yp(1);
f2 = (a(1)*sin(y(1))-a(5)+a(6)*y(1)+a(7)*sin(y(2)-y(1)))/yp(1)*a(8)*cos(y(2)-y(1)) - yp(2);
f = [f1 ; f2] ;
end
Then, the initial conditions and integration timespan can be set in order to call ode15i:
tspan = [0 10];
y0 = [1; 1] ;
yp0 = fsolve(#(yp)cp_ode(0,y0,yp,a),<yp0_guess>);
a = ones(1,8) ;
[t,y] = ode15i(#(t,y,yp)cp_ode(t,y,yp,a), tspan, y0, yp0);
It has to be noted that the initial conditions t, y, yp should fulfill the equation f(t, y, yp)=0. Here an fsolve is used to satisfy this condition.
The use of annonymus functions is to define the function with the parameters as inputs and then execute the ODE solver having defined the parameters in the main code.

Finding solution to Cauchy prob. in Matlab

I need some help with finding solution to Cauchy problem in Matlab.
The problem:
y''+10xy = 0, y(0) = 7, y '(0) = 3
Also I need to plot the graph.
I wrote some code but, I'm not sure whether it's correct or not. Particularly in function section.
Can somebody check it? If it's not correct, where I made a mistake?
Here is separate function in other .m file:
function dydx = funpr12(x,y)
dydx = y(2)+10*x*y
end
Main:
%% Cauchy problem
clear all, clc
xint = [0,5]; % interval
y0 = [7;3]; % initial conditions
% numerical solution using ode45
sol = ode45(#funpr12,xint,y0);
xx = [0:0.01:5]; % vector of x values
y = deval(sol,xx); % vector of y values
plot(xx,y(1,:),'r', 'LineWidth',3)
legend('y1(x)')
xlabel('x')
ylabel('y(x)')
I get this graph:
ode45 and its related ilk are only designed to solve first-order differential equations which are of the form y' = .... You need to do a bit of work if you want to solve second-order differential questions.
Specifically, you'll have to represent your problem as a system of first-order differential equations. You currently have the following ODE:
y'' + 10xy = 0, y(0) = 7, y'(0) = 3
If we rearrange this to solve for y'', we get:
y'' = -10xy, y(0) = 7, y'(0) = 3
Next, you'll want to use two variables... call it y1 and y2, such that:
y1 = y
y2 = y'
The way you have built your code for ode45, the initial conditions that you specified are exactly this - the guess using y and its first-order guess y'.
Taking the derivative of each side gives:
y1' = y'
y2' = y''
Now, doing some final substitutions we get this final system of first-order differential equations:
y1' = y2
y2' = -10*x*y1
If you're having trouble seeing this, simply remember that y1 = y, y2 = y' and finally y2' = y'' = -10*x*y = -10*x*y1. Therefore, you now need to build your function so that it looks like this:
function dydx = funpr12(x,y)
y1 = y(2);
y2 = -10*x*y(1);
dydx = [y1 y2];
end
Remember that the vector y is a two element vector which represents the value of y and the value of y' respectively at each time point specified at x. I would also argue that making this an anonymous function is cleaner. It requires less code:
funpr12 = #(x,y) [y(2); -10*x*y(1)];
Now go ahead and solve it (using your code):
%%// Cauchy problem
clear all, clc
funpr12 = #(x,y) [y(2); -10*x*y(1)]; %// Change
xint = [0,5]; % interval
y0 = [7;3]; % initial conditions
% numerical solution using ode45
sol = ode45(funpr12,xint,y0); %// Change - already a handle
xx = [0:0.01:5]; % vector of x values
y = deval(sol,xx); % vector of y values
plot(xx,y(1,:),'r', 'LineWidth',3)
legend('y1(x)')
xlabel('x')
ylabel('y(x)')
Take note that the output when simulating the solution to the differential equation by deval will be a two column matrix. The first column is the solution to the system while the second column is the derivative of the solution. As such, you'll want to plot the first column, which is what the plot syntax is doing.
I get this plot now:

Using interp1 in an ODE function [MATLAB]

I have here an ODE to solve that has a test parameter a.
I would like a to be a function of temperature T (in this code it is solved as X(2) since it varies with time).
I would like to base it off experimental values of a and T.
Hence, I am thinking of doing it along the lines of interp1.
Here is my test dummy ODE.
function xprime = RabbitTemp(t,X)
% Model of Rabbit Population
% where,
% Xo = Initial Population of Rabbits
% X(1) = Population density of Rabbit
% X(2) = Temperature T (that varies with time)
% a = test parameter
% Interpolate here
Texptdata = [1 2 3 4];
aexptdata =[10 14 19 30];
a= interp1(Texptdata,aexptdata,X(2),'spline');
% ODE
dx = [0 0];
dx(1) = (X(1))*(1 - X(1)*a - 3*(X(2))));
dx(2) = sin(t);
xprime = [dx(1) dx(2)]';
end
I've tried running the code with my solver and it does compile fine.
However I am just wondering if the ODE solver is calling the correct interpolated a corresponding to the correct corresponding value of X(2). I cannot seem to figure out how to verify this.
Can anyone help me verify this or point me to how I can go about doing it? Much appreciated!

MATLAB solve Ordinary Differential Equations

How can I use matlab to solve the following Ordinary Differential Equations?
x''/y = y''/x = -( x''y + 2x'y' + xy'')
with two known points, such as t=0: x(0)= x0, y(0) = y0; t=1: x(1) = x1, y(1) = y1 ?
It doesn't need to be a complete formula if it is difficult. A numerical solution is ok, which means, given a specific t, I can get the value of x(t) and y(t).
If matlab is hard to do this, mathematica is also OK. But as I am not familiar with mathematica, so I would prefer matlab if possible.
Looking forward to help, thanks!
I asked the same question on stackexchange, but haven't get good answer yet.
https://math.stackexchange.com/questions/812985/matlab-or-mathematica-solve-ordinary-differential-equations
Hope I can get problem solved here!
What I have tried is:
---------MATLAB
syms t
>> [x, y] = dsolve('(D2x)/y = -(y*D2x + 2Dx*Dy + x*D2y)', '(D2y)/x = -(y*D2x + 2Dx*Dy + x*D2y)','t')
Error using sym>convertExpression (line 2246)
Conversion to 'sym' returned the MuPAD error: Error: Unexpected 'identifier'.
[line 1, col 31]
Error in sym>convertChar (line 2157)
s = convertExpression(x);
Error in sym>convertCharWithOption (line 2140)
s = convertChar(x);
Error in sym>tomupad (line 1871)
S = convertCharWithOption(x,a);
Error in sym (line 104)
S.s = tomupad(x,'');
Error in dsolve>mupadDsolve (line 324)
sys = [sys_sym sym(sys_str)];
Error in dsolve (line 186)
sol = mupadDsolve(args, options);
--------MATLAB
Also, I tried to add conditions, such as x(0) = 2, y(0)=8, x(1) = 7, y(1) = 18, and the errors are still similar. So what I think is that this cannot be solve by dsolve function.
So, again, the key problem is, given two known points, such as when t=0: x(0)= x0, y(0) = y0; t=1: x(1) = x1, y(1) = y1 , how I get the value of x(t) and y(t)?
Update:
I tried ode45 functions. First, in order to turn the 2-order equations into 1-order, I set x1 = x, x2=y, x3=x', x4=y'. After some calculation, the equation becomes:
x(1)' = x(3) (1)
x(2)' = x(4) (2)
x(3)' = x(2)/x(1)*(-2*x(1)*x(3)*x(4)/(1+x(1)^2+x(2)^2)) (3)
x(4)' = -2*x(1)*x(3)*x(4)/(1+x(1)^2+x(2)^2) (4)
So the matlab code I wrote is:
myOdes.m
function xdot = myOdes(t,x)
xdot = [x(3); x(4); x(2)/x(1)*(-2*x(1)*x(3)*x(4)/(1+x(1)^2+x(2)^2)); -2*x(1)*x(3)*x(4)/(1+x(1)^2+x(2)^2)]
end
main.m
t0 = 0;
tf = 1;
x0 = [2 3 5 7]';
[t,x] = ode45('myOdes',[t0,tf],x0);
plot(t,x)
It can work. However, actually this is not right. Because, what I know is that when t=0, the value of x and y, which is x(1) and x(2); and when t=1, the value of x and y. But the ode functions need the initial value: x0, I just wrote the condition x0 = [2 3 5 7]' randomly to help this code work. So how to solve this problem?
UPDATE:
I tried to use the function bvp4c after I realized that it is a boundary value problem and the following is my code (Suppose the two boundry value conditions are: when t=0: x=1, y=3; when t=1, x=6, y=9. x is x(1), y is x(2) ):
1. bc.m
function res = bc(ya,yb)
res = [ ya(1)-1; ya(2)-3; yb(1) - 6; yb(2)-9];
end
2. ode.m
function dydx = ode(t,x)
dydx = [x(3); x(4); x(2)/x(1)*(-2*x(1)*x(3)*x(4)/(1+x(1)^2+x(2)^2)); -2*x(1)*x(3)*x(4)/(1+x(1)^2+x(2)^2)];
end
3. mainBVP.m
solinit = bvpinit(linspace(0,6,10),[1 0 -1 0]);
sol = bvp4c(#ode,#bc,solinit);
t = linspace(0,6);
x = deval(sol,t);
plot(t,x(1,:));
hold on
plot(t,x(2,:));
plot(t,x(3,:));
plot(t,x(4,:));
x(1,:)
x(2,:)
It can work, but I don't know whether it is right. I will check it again to make sure it is the right code.
As mentioned, this isn't a math site, so try to give code or something showing some effort.
However, the first step you need to do is turn the DE into normal form (i.e., no 2nd derivatives). You do this by making a separate variable equal to the derivative. Then, you use
syms x y % or any variable instead of x or y
to define variables as symbolic. Use matlabfunction to create a symbolic function based on these variables. Finally, you can use the ode45 function to solve the symbolic function while passing variable values. I recommend you look up the full documentation in matlab in order to understand it better, but here is a very basic syntax:
MyFun= matlabFunction(eq,'vars',{x,y});
[xout,yout]=ode45(#(x,Y) MyFun(variables),[variable values],Options);
Hopefully this puts you in the right direction, so try messing around with it and provide code if you need more help.
EDIT:
This is how I would solve the problem. Note: I don't really like the matlabFunction creator but this is simply a personal preference for various reasons I won't go into.
% Seperate function of the first order state equations
function dz = firstOrderEqns(t,z)
dz(4,1) = 0;
dz(1) = -2.*z(3).*z(1).*z(4)./(1 + z(4).^2 + z(2).^2);
dz(2) = z(1);
dz(3) = -2.*z(2).*z(3).*z(1)./(1 + z(4).^2 + z(2).^2);
dz(4) = z(3);
end
% runfirstOrderEqns
%% Initial conditions i.e. # t=0
z1 = 5; % dy/dt = 5 (you didn't specify these initial conditions,
% these will depend on the system which you didn't really specify
z2 = 0; % y = 0
z3 = 5; % dx/dt = 5 (The same as for z1)
z4 = 0; % x = 0
IC = [z1, z2, z3, z4];
%% Run simulation
% Time vector: i.e closed interval [0,20]
t = [0,20]; % This is where you have to know about your system
% i.e what is it's time domain.
% Note: when a system has unstable poles at
% certain places the solver can crash you need
% to understand these.
% using default settings (See documentation ode45 for 'options')
[T,Y] = ode45(#firstOrderEqns,t,IC);
%% Plot function
plot(T,Y(:,1),'-',T,Y(:,2),'-.',T,Y(:,3),':',T,Y(:,4),'.');
legend('dy/dt','y','dx/dt','x')
As in my comments I have made a lot of assumtions that you need to fix for example, you didn't specify what the initial conditions for the first derivatives of the states are i.e. (z1, z3) which is important for the response of the system. Also you didn't specify the time interval your interested for the simulation etc.
Note: The second m file can be used with any state function in the correct format
The following is the answer we finally get #Chriso: use matlab bvp4c function to solve this boundary value problem (Suppose the two boundry value conditions are: when t=0: x=1, y=3; when t=1, x=6, y=9. x is x(1), y is x(2) ):
1. bc.m
function res = bc(ya,yb)
res = [ ya(1)-1; ya(2)-3; yb(1) - 6; yb(2)-9];
end
2. ode.m
function dydx = ode(t,x)
dydx = [x(3); x(4); x(2)/x(1)*(-2*x(1)*x(3)*x(4)/(1+x(1)^2+x(2)^2)); -2*x(1)*x(3)*x(4)/(1+x(1)^2+x(2)^2)];
end
3. mainBVP.m
solinit = bvpinit(linspace(0,6,10),[1 0 -1 0]);
sol = bvp4c(#ode,#bc,solinit);
t = linspace(0,6);
x = deval(sol,t);
plot(t,x(1,:));
hold on
plot(t,x(2,:));
plot(t,x(3,:));
plot(t,x(4,:));
x(1,:)
x(2,:)

How do you plot nonlinear differential equations in matlab

Dx=y
Dy=-k*y-x^3+9.8*cos(t)
inits=('x(0)=0,y(0)=0')
these are the differential equations that I wanted to plot.
first, I tried to solve the differential equation and then plot the graph.
Dsolve('Dx=y','Dy=-k*y-x^3+9.8*cos(t)', inits)
like this, however, there was no explicit solution for this system.
now i am stuck :(
how can you plot this system without solving the equations?
First define the differential equation you want to solve. It needs to be a function that takes two arguments - the current time t and the current position x, and return a column vector. Instead of x and y, we'll use x(1) and x(2).
k = 1;
f = #(t,x) [x(2); -k * x(2) - x(1)^3 + 9.8 * cos(t)];
Define the timespan you want to solve over, and the initial condition:
tspan = [0, 10];
xinit = [0, 0];
Now solve the equation numerically using ode45:
ode45(f, tspan, xinit)
which results in this plot:
If you want to get the values of the solution at points in time, then just ask for some output arguments:
[t, y] = ode45(f, tspan, xinit);
You can plot the phase portrait x against y by doing
plot(y(:,1), y(:,2)), xlabel('x'), ylabel('y'), grid
which results in the following plot