Second Order Diff Eq with ode45 in Matlab - matlab

So I need to solve x''(t) = -x(t)^p with initial conditions x(0)= 0 and v(0) = x'(0) = v_o = 1.
The value of the parameter p is 1.
This is what I have:
function [t, velocity, x] = ode_oscilation(p)
y=[0;0;0];
% transform system to the canonical form
function y = oscilation_equation(x,p)
y=zeros(2,1);
y(1)=y(2);
y(2)=-(x)^p;
% to make matlab happy we need to return a column vector
% so we transpose (note the dot in .')
y=y.';
end
tspan=[0, 30]; % time interval of interest
[t,velocity,x] = ode45(#oscilation_equation, tspan, 1);
t = y(:,1);
xposition=y(:,3);
velocity=y(:,2);
end
and this is the error message I receive:
ode_oscillation(1)
Error using odearguments (line 91)
ODE_OSCILLATION/OSCILATION_EQUATION must return a
column vector.
Error in ode45 (line 114)
[neq, tspan, ntspan, next, t0, tfinal, tdir, y0, f0,
odeArgs, odeFcn, ...
Error in ode_oscillation (line 17)
[t,velocity,x] = ode45(#oscilation_equation, tspan,1);

There's a few things going wrong here. First, from help ode45:
ode45 Solve non-stiff differential equations, medium order method.
[TOUT,YOUT] = ode45(ODEFUN,TSPAN,Y0) with TSPAN = [T0 TFINAL] integrates
the system of differential equations y' = f(t,y) from time T0 to TFINAL
with initial conditions Y0.
Note that ode45 expects a function f(t,y), where size(t) == [1 1] for time and size(y) == [1 N] or [N 1] for solution values. Your oscilation_equation has the order of input arguments inverted, and you input a constant parameter p instead of time t.
Also, the initial conditions Y0 should have the same size as y; so size(y0) == [N 1] or [1 N]. You just have 1, which is clearly causing errors.
Also, your output arguments t, xposition and velocity will be completely ignored and erroneous, since y is not set as output argument from ode45, and most of all, their names do not correspond to ode_oscilation's output arguments. Also, their order of extracting from columns of y is incorrect.
So, in summary, change everything to this:
function [t, v, x] = ode_oscilation(p)
% initial values
y0 = [0 1];
% time interval of interest
tspan =[0 30];
% solve system
[t,y] = ode45(#(t,y) [y(2); -y(1)^p], tspan, y0);
% and return values of interest
x = y(:,1);
v = y(:,2);
end

Related

How to write an Ordinary Differential Equation in MATLAB?

I tried writing an Ordinary Differential Equation in MATLAB.
I wrote this code:
function [y] = odefun(t,y)
t = [0:0.01:10];
y = [0 0]';
y(1) = y(2);
y(2) = sin(2*t)-2*y(2)-2*y(1); % I get an error here
end
I get an error in the last line in this code. MATLAB doesn't show me what the error is. It just tells me I have an error in that line.
Why do I get this error and how to resolve it?
What you want is to carefully read the documentation of the diverse ode solvers and the examples there and then correct your code to something like
% Solve ODE y''(t)+2*y'(t)+2*y(t) = sin(2*t), y(0)=y'(0)=0
function ydot = odefun(t,y)
ydot = zeros_like(y)
ydot(1) = y(2);
ydot(2) = sin(2*t)-2*y(2)-2*y(1);
end
% or
% odefun = #(y,t) [ y(2); sin(2*t)-2*y(2)-2*y(1) ]
% define sample points
tspan = [0:0.01:10];
% define initial value to t=tspan(1)
y0 = [0 0]';
[ t, y ] = ode45(odefunc, tspan, y0)
% t,y now contain the times and values that
% the solution was actually computed for.
You try to assign to y(2) a vector of 1001 elements:
>> size(sin(2*t)-2*y(2)-2*y(1))
ans =
1 1001
The error message is pretty clear:
In an assignment A(:) = B, the number of elements in A and B must be the same.
Also, y and t are never use since you redefined them in the function.

Too Many Input Arguments Matlab ode45

I am trying to write a simple Matlab code to model a projectile. Whenever I try to run the code I get an error saying there are too many input arguments. I am running the code with
model1(44.7, 45)
function[] = model1(vel, angle)
close all;
tspan = [0 3];
x0 = [0; 0.915; vel*cos(angle); vel*sin(angle)];
[x] = ode45(#ball, tspan, x0);
function xdot = ball(x)
g = 9.81;
xdot = [x(3); x(4); 0; -g];
end
end
Error using model1/ball
Too many input arguments.
Error in odearguments (line 87)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options,
varargin);
Error in model1 (line 9)
[x] = ode45(#ball, tspan, x0);
I'd appreciate any advice!
The error was (what I also committed many times in the past) that you have to pass the independent variable (time, in this case) too.
function [t, x] = model1(vel, angle)
tspan = [0 3];
x0 = [0; 0.915; vel*cos(angle); vel*sin(angle)];
[t, x] = ode45(#ball, tspan, x0);
end
function xdot = ball(t,x)
g = 9.81;
xdot = [x(3); x(4); 0; -g];
end
I modified your code to return the solution and the corresponding time steps. Moreover, I removed ball to be a nested function.

MATLAB - How to read a single value from a vector? (ode45 involved)

I'm trying to work with a code that involves ode45, in the one in the equation that will be solved I have to introduce a single value from a vector that will change depending on the time the equation is solved, I mean if it is x=x(0) then u1(1) and u2(t), when x=x(1) then u1(2), u2(2)... This is my code:
function [sal] = scobe1
clear
clc
global a;
a=1;
assignin('base','a',a)
tspan = [0; 180];
x0 = [80; 0];
[t,x] = ode45(#f,tspan,x0);
sal=[t,x]
figure
subplot(2,1,1)
plot(t,x(:,1),'k-');
subplot(2,1,2)
plot(t,x(:,2),'b-');
function dxdt = f(t,x)
global a s1 u1 u2 newData;
newData=importdata('datosnoembarazo.mat');
assignin('base','newData',newData);
u1=getfield(newData,'glucosa4dias');
assignin('base','u1',u1);
u2=getfield(newData,'insulina4dias');
assignin('base','u2',u2);
u1=getfield(newData,'glucosa4dias');
assignin('base','u1',u1);
u2=getfield(newData,'insulina4dias');
assignin('base','u2',u2);
if (a<=s1)
dxdt = [
(-4.9e-2-x(2))*x(1) + (4.42 + u1(a)) %(1) IN HERE u1 IS THE VECTOR'S NAME
-9.1e-2*x(2) + u2(a) %(2) IN HERE u2 IS THE VECTOR'S NAME
];
a=a+1
assignin('base','a',a);
else return
end
The problem is that it sends me this error: And I don't know what is wrong with the code, or what else can I do in order for it to read it, can you please help me? Thanks
Error in scobe1>f (line 36)
global a s1 s2 u1 u2 newData;
Error using feval
Output argument "dxdt" (and maybe others) not assigned during call to
"C:\Users\AnnieA\Dropbox\Tesis (A. Olay)\GUI Examples\Resumen de Modelos\scobe1.m>f".
Error in odearguments (line 87)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode45 (line 113)
[neq, tspan, ntspan, next, t0, tfinal, tdir, y0, f0, odeArgs, odeFcn, ...
Error in scobe1 (line 25)
[t,x] = ode45(#f,tspan,x0);
Your function function dxdt = f(t,x) has two branches in the if statement: If a<=s1, then dxdt gets assigned correctly. If a>s1, dxdt is not assigned at all. You can fix the error by assigning a value to dxdt in the else branch of your if statment before you return. I am not sure what an appropriate value would be in this case. Perhaps 0?

Taylor Method ODE

I am trying to implement the Taylor method for ODEs in MatLab:
My code (so far) looks like this...
function [x,y] = TaylorEDO(f, a, b, n, y0)
% syms t
% x = sym('x(t)'); % x(t)
% f = (t^2)*x+x*(1-x);
h = (b - a)/n;
fprime = diff(f);
f2prime = diff(fprime);
y(0) = y0,
for i=1:n
T((i-1)*h, y(i-1), n) = double(f((i-1)*h, y(i-1)))+(h/2)*fprime((i-1)*h, y(i-1))
y(i+1) = w(i) + h*T(t(i), y(i), n);
I was trying to use symbolic variables, but I donĀ“t know if/when I have to use double.
I also tried this other code, which is from a Matlab function, but I do not understand how f should enter the code and how this df is calculated.
http://www.mathworks.com/matlabcentral/fileexchange/2181-numerical-methods-using-matlab-2e/content/edition2/matlab/chap_9/taylor.m
As error using the function from this link, I got:
>> taylor('f',0,2,0,20)
Error using feval
Undefined function 'df' for input arguments of type 'double'.
Error in TaylorEDO (line 28)
D = feval('df',tj,yj)
The f I used here was
syms t
x = sym('x(t)'); % x(t)
f = (t^2)*x+x*(1-x);
This is a numerical method, so it needs numerical functions. However, some of them are computed from the derivatives of the function f. For that, you need symbolic differentiation.
Relevant Matlab commands are symfun (create a symbolic function) and matlabFunction (convert a symbolic function to numerical).
The code you have so far doesn't seem salvageable. You need to start somewhere closer to basics, e.g., "Matlab indices begin at 1". So I'll fill the gap (computation of df) in the code you linked to. The comments should explain what is going on.
function [T,Y] = taylor(f,a,b,ya,m)
syms t y
dfs(1) = symfun(f, [t y]); % make sure that the function has 2 arguments, even if the user passes in something like 2*y
for k=1:3
dfs(k+1) = diff(dfs(k),t)+f*diff(dfs(k),y); % the idea of Taylor method: calculate the higher derivatives of solution from the ODE
end
df = matlabFunction(symfun(dfs,[t y])); % convert to numerical function; again, make sure it has two variables
h = (b - a)/m; % the rest is unchanged except one line
T = zeros(1,m+1);
Y = zeros(1,m+1);
T(1) = a;
Y(1) = ya;
for j=1:m
tj = T(j);
yj = Y(j);
D = df(tj,yj); % syntax change here; feval is unnecessary with the above approach to df
Y(j+1) = yj + h*(D(1)+h*(D(2)/2+h*(D(3)/6+h*D(4)/24)));
T(j+1) = a + h*j;
end
end
Example of usage:
syms t y
[T, Y] = taylor(t*y, 0, 1, 2, 100);
plot(T,Y)

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,:)