Solving a differential equation in Matlab for different inputs - matlab

How do you look at only the endpoint in time (12 in this case) and see how changing a parameter at that point, such as a scalar in one of the differential equations, changes the data?
function test
options = odeset('RelTol',1e-4,'AbsTol',[1e-4 1e-4 1e-5]);
[T,Y] = ode45(#rigid,[0 12],[0 1 1],options);
plot(T,Y(:,1),'-',T,Y(:,2),'-.',T,Y(:,3),'.')
function dy = rigid(t,y)
dy = zeros(3,1); % a column vector
dy(1) = y(2) * y(3);
dy(2) = -y(1) * y(3);
dy(3) = -0.51 * y(1) * y(2);
end
end

You can just add a parameter to your ode, and accumulate the results in cell arrays.
function test
close all
options = odeset('RelTol',1e-4,'AbsTol',[1e-4 1e-4 1e-5]);
%// List of parameter values.
kList = 0:0.5:2;
%// Cells were save the single time histories.
tList = cell(length(kList),1);
yList = cell(length(kList),1);
%// Last values of each integration.
yEnd = zeros(length(kList), 3);
%// Loop over the parameter values.
for i = 1:length(kList)
%// Select the parameter value.
k = kList(i);
%// Call ode45 with k at the end.
[tList{i},yList{i}] = ode45(#rigid,[0 12],[0 1 1],options,k);
figure();
plot(tList{i},yList{i}(:,1),'-', ...
tList{i},yList{i}(:,2),'-.', ...
tList{i},yList{i}(:,3),'.');
yEnd(i,:) = yList{i}(end,:);
end
disp(yEnd);
%// Make the ode dependent from k.
function dy = rigid(t,y,k)
dy = zeros(3,1); % a column vector
dy(1) = y(2) * y(3);
dy(2) = -y(1) * y(3);
dy(3) = k * y(1) * y(2);
end
end

Related

what is wrong in Second Order Differential Equation?

My code is
I am trying to plot a graph of second order differential equation
clc;
funcprot(0);
function dx = f(t,x)
dx(1) = x(2);
dx(2) = sin(2 * t);
endfunction
t = 0: 0.1 : 4 * %pi;
y = ode ([0,-1/2],0,t,f);
plot2d(t',[y(1,:)',y(2,:)']);
xlabel('t'); ylabel('y and derivative');
xtitle('Plot of solution of 2nd order ODE')
Just transpose the initial condition:
clc;
funcprot(0);
function dx = f(t,x)
dx(1) = x(2);
dx(2) = sin(2 * t);
endfunction
t = 0: 0.1 : 4 * %pi;
y = ode ([0,-1/2]',0,t,f);
plot2d(t',[y(1,:)',y(2,:)']);
xlabel('t'); ylabel('y and derivative');
xtitle('Plot of solution of 2nd order ODE')

How to get the roots of these equations with flexible parameters by fsolve function?

I write two mfiles to solve the roots t and p of two equations. There is a flexible parameter n used in equation which changes from 1 to 100. Now the code can only solve the roots as n = 100 for 100 time instead of 1 to 100. How to correct it?
file 1:
function q=CSMA(x)
m=5;
W=32;
p=x(1);
t=x(2);
for n = 1:100;
q(1)=(1-2*p)*(1+W)+p*W*(1-(2*p)^m)-2*(1-2*p)/t;
q(2)=(1-(1-t)^(n-1))-p;
end
end
file 2:
N = 100;
the_roots = zeros(1, N);
for n = 1:N
y = fsolve('CSMA', [0.1, 0.1], optimset('Display', 'off'));
p = y(1);
t = y(2);
the_roots(n)= t;
end
figure;
plot(the_roots, 'b-');
You need to pass the variable n to your function as a parameter. You could for example change your CSMA function like this:
function q=CSMA(x,n)
m=5;
W=32;
p=x(1);
t=x(2);
q(1)=(1-2*p)*(1+W)+p*W*(1-(2*p)^m)-2*(1-2*p)/t;
q(2)=(1-(1-t)^(n-1))-p;
end
And then the optimization could look like this using a function handle:
N = 100;
the_roots = zeros(1, N);
for n = 1:N
f = #(x) CSMA(x,n);
y = fsolve(f, [0.1, 0.1], optimset('Display', 'off'));
p = y(1);
t = y(2);
the_roots(n)= t;
end
figure;
plot(the_roots, 'b-');
The plotted output looks like this:

Modelling Projectile Motion using Matlab ode45

So I am trying to model simple projectile motion (no air resistance etc) using the ode45 solver in Matlab. This is my code so far:
function [x,y] = trajectory_without_AR_45(v0,theta, dt)
%Path of mortar without air resistance using ode45
g = 9.81;
t_start = 0;
t_end = 100;
%Initial Conditions
y01 = 0; %initial x
y02 = v0 * cos(theta); %finding initial velocity in x direction
y03 = 0; %initial y
y04 = v0 * sin(theta); % finding intial velocity in y direction
y0 = [y01;y02;y03;y04];
%Derivatives
dy1 = y0(2); %vx
dy2 = 0; %ax
dy3 = y0(4); %vy
dy4 = -g; %ay
dy = [dy1;dy2;dy3;dy4];
%Using ODE45
f = # (t, y) (dy);
solution = ode45(f, [t_start, t_end], y0);
t = t_start : 0.01: t_end;
y = deval(solution, t);
plot (y(:,1), y(:,3)); %plotting trajectory
end
However, the plot I am getting is just a straight line which clearly is not correct. Any help would be appreciated.
I think you're not calling the ode solver properly, you only seem to be using the initial conditions to compute dy, which is wrong. Best to put the ode function in a separate function (file). For example, the following is in missile.m:
function dY = missile(t,Y)
g = 9.81;
dY(1) = Y(2); %vx
dY(2) = 0; %ax
dY(3) = Y(4); %vy
dY(4) = -g; %ay
end
Which you would then call as follows:
t_start = 0;
t_end = 2.3; % changed to something more consistent with when y<0
v0 = 10; % made up
theta=pi/4; % made up
y01 = 0; %initial x
y02 = v0 * cos(theta); %finding initial velocity in x direction
y03 = 0; %initial y
y04 = v0 * sin(theta); % finding intial velocity in y direction
y0 = [y01;y02;y03;y04];
opts = odeset('MaxStep',0.01,'InitialStep',0.001);
[t,y] = ode45(#missile, [t_start, t_end], y0, opts);
plot(t,y)
legend('x','dx','y','dy')
which gives the following results:

Solving 2nd order differential equation with boundary condition z(inf) = 0

How can I solve a 2nd order differential equation with boundary condition like z(inf)?
2(x+0.1)·z'' + 2.355·z' - 0.71·z = 0
z(0) = 1
z(inf) = 0
z'(0) = -4.805
I can't understand where the boundary value z(inf) is to be used in ode45() function.
I used in the following condition [z(0) z'(0) z(inf)], but this does not give accurate output.
function [T, Y]=test()
% some random x function
x = #(t) t;
t=[0 :.01 :7];
% integrate numerically
[T, Y] = ode45(#linearized, t, [1 -4.805 0]);
% plot the result
plot(T, Y(:,1))
% linearized ode
function dy = linearized(t,y)
dy = zeros(3,1);
dy(1) = y(2);
dy(2) = y(3);
dy(3) = (-2.355*y(2)+0.71*y(1))/((2*x(t))+0.2);
end
end
please help me to solve this differential equation.
You seem to have a fairly advanced problem on your hands, but very limited knowledge of MATLAB and/or ODE theory. I'm happy to explain more if you want, but that should be in chat (I'll invite you) or via personal e-mail (my last name AT the most popular mail service from Google DOT com)
Now that you've clarified a few things and explained the whole problem, things are a bit more clear and I was able to come up with a reasonable solution. I think the following is at least in the general direction of what you'd need to do:
function [tSpan, Y2, Y3] = test
%%# Parameters
%# Time parameters
tMax = 1e3;
tSpan = 0 : 0.01 : 7;
%# Initial values
y02 = [1 -4.805]; %# second-order ODE
y03 = [0 0 4.8403]; %# third-order ODE
%# Optimization options
opts = optimset(...
'display', 'off',...
'TolFun' , 1e-5,...
'TolX' , 1e-5);
%%# Main procedure
%# Find X so that z2(t,X) -> 0 for t -> inf
sol2 = fminsearch(#obj2, 0.9879680932400429, opts);
%# Plug this solution into the original
%# NOTE: we need dense output, which is done via deval()
Z = ode45(#(t,y) linearized2(t,y,sol2), [0 tMax], y02);
%# plot the result
Y2 = deval(Z,tSpan,1);
plot(tSpan, Y2, 'b');
%# Find X so that z3(t,X) -> 1 for t -> inf
sol3 = fminsearch(#obj3, 1.215435887288112, opts);
%# Plug this solution into the original
[~, Y3] = ode45(#(t,y) linearized3(t,y,sol3), tSpan, y03);
%# plot the result
hold on, plot(tSpan, Y3(:,1), 'r');
%# Finish plots
legend('Second order ODE', 'Third order ODE')
xlabel('T [s]')
ylabel('Function value [-]');
%%# Helper functions
%# Function to optimize X for the second-order ODE
function val = obj2(X)
[~, y] = ode45(#(t,y) linearized2(t,y,X), [0 tMax], y02);
val = abs(y(end,1));
end
%# linearized second-order ODE with parameter X
function dy = linearized2(t,y,X)
dy = [
y(2)
(-2.355*y(2) + 0.71*y(1))/2/(X*t + 0.1)
];
end
%# Function to optimize X for the third-order ODE
function val = obj3(X3)
[~, y] = ode45(#(t,y) linearized3(t,y,X3), [0 tMax], y03);
val = abs(y(end,2) - 1);
end
%# linearized third-order ODE with parameters X and Z
function dy = linearized3(t,y,X)
zt = deval(Z, t, 1);
dy = [
y(2)
y(3)
(-1 -0.1*zt + y(2) -2.5*y(3))/2/(X*t + 0.1)
];
end
end
As in my comment above, I think you're confusing a couple of things. I suspect this is what is requested:
function [T,Y] = test
tMax = 1e3;
function val = obj(X)
[~, y] = ode45(#(t,y) linearized(t,y,X), [0 tMax], [1 -4.805]);
val = abs(y(end,1));
end
% linearized ode with parameter X
function dy = linearized(t,y,X)
dy = [
y(2)
(-2.355*y(2) + 0.71*y(1))/2/(X*t + 0.1)
];
end
% Find X so that z(t,X) -> 0 for t -> inf
sol = fminsearch(#obj, 0.9879);
% Plug this ssolution into the original
[T, Y] = ode45(#(t,y) linearized(t,y,sol), [0 tMax], [1 -4.805]);
% plot the result
plot(T, Y(:,1));
end
but I can't get it to converge anymore for tMax beyond 1000 seconds. You may be running into the limits of ode45 capabilities w.r.t. accuracy (switch to ode113), or your initial value is not accurate enough, etc.

Vectorizing ODE in Octave / Matlab

If I have an ode and wrote it in two ways, like here:
function re=rabdab()
x=linspace(0,2000,2000)';
tic;
[T,Y] = ode45(#fun,[x],[0 1 1]);
[T,Y] = ode45(#fun,[x],[0 1 1]);
[T,Y] = ode45(#fun,[x],[0 1 1]);
toc;
tic;
[A,B] = ode45(#fun2,[x],[0 1 1]);
[A,B] = ode45(#fun2,[x],[0 1 1]);
[A,B] = ode45(#fun2,[x],[0 1 1]);
toc;
function dy = fun(t,y)
dy = zeros(3,1); % a column vector
dy = [y(2) * y(3);...
-y(1) * y(3);...
-0.51 * y(1) * y(2);];
function dy = fun2(t,y)
dy = zeros(3,1); % a column vector
dy(1) = y(2) * y(3);
dy(2) = -y(1) * y(3);
dy(3) = -0.51 * y(1) * y(2);
There is almost no difference in time. One takes just as long as the other. But I thought that fun is the vectorized version of fun2. Or am I mistaken here?
The purpose is to speed up my code a little. The example is taken from the matlab webpage.
I think I haven't really understood what "vectorized" means.
If this is already vectorized, what would a non-vectorized code look like?
Vectorization is a concept which is closely related to functional programming. In MATLAB it means performing operations on arrays (vectors or matrices) without implicitly writing a loop.
For example, if you were to compute the function f(x) = 2x for every integer x between 1 and 100, you could write:
for x = 1:100
f(x) = 2 * x;
end
which is not vectorized code. The vectorized version is:
x = 1:100; %// Declare a vector of integer values from 1 to 100
f = 2 * x; %// Vectorized operation "*"
or even shorter:
f = 2 * (1:100);
MATLAB is an interpreted language, so obviously the interpreter translates this into some kind of loop "under the hood", but it's optimized and is usually much faster than actually interpreting a loop (read this question for reference). Well, sort of -- it's been like that until the recent releases of MATLAB, where JIT acceleration has been integrated (read here).
Now getting back to your code: what you have here is two vectorized versions of your code: one that concatenates vertically three values and one that directly assigns these values into a column vector. That's basically the same thing. Should you have done it with an explicit for loop, this would not have been "vectorized". Regarding the actual performance gain from "vectorizing" a loop (that is, converting a for loop into a vectorized operation), this depends on the how fast the for loop actually was due to JIT acceleration in the first place.
It doesn't seem that there's much to be done to speed up your code. Your functions are pretty basic, so it boils down to the internal implementation of ode45, which you cannot modify.
If you're interested in further reading about vectorization and writing faster MATLAB code in general, here's an interesting article: Loren on the Art of MATLAB: "Speeding Up MATLAB Applications".
Happy coding!
While the previous answer is correct in general terms, vectorized in the context of ODEs means something more specific. In short, a function f(t,y) is vectorized iff f(t,[y1 y2 ...]) returns [f(t,y1) f(t,y2) ...], for y1,y2 column vectors. As per the documentation [1], "this allows the solver to reduce the number of function evaluations required to compute all the columns of the Jacobian matrix."
Functions fun3 and fun4 below are properly vectorized in the ODE sense:
function re=rabdab()
x=linspace(0,20000,20000)';
opts=odeset('Vectorized','on');
tic;
[T,Y] = ode45(#fun,[x],[0 1 1]);
[T,Y] = ode45(#fun,[x],[0 1 1]);
[T,Y] = ode45(#fun,[x],[0 1 1]);
toc;
tic;
[A,B] = ode45(#fun2,[x],[0 1 1]);
[A,B] = ode45(#fun2,[x],[0 1 1]);
[A,B] = ode45(#fun2,[x],[0 1 1]);
toc;
tic;
[A,B] = ode45(#fun3,[x],[0 1 1],opts);
[A,B] = ode45(#fun3,[x],[0 1 1],opts);
[A,B] = ode45(#fun3,[x],[0 1 1],opts);
toc;
tic;
[A,B] = ode45(#fun4,[x],[0 1 1],opts);
[A,B] = ode45(#fun4,[x],[0 1 1],opts);
[A,B] = ode45(#fun4,[x],[0 1 1],opts);
toc;
function dy = fun(t,y)
dy = zeros(3,1); % a column vector
dy = [y(2) * y(3);...
-y(1) * y(3);...
-0.51 * y(1) * y(2);];
function dy = fun2(t,y)
dy = zeros(3,1); % a column vector
dy(1) = y(2) * y(3);
dy(2) = -y(1) * y(3);
dy(3) = -0.51 * y(1) * y(2);
function dy = fun3(t,y)
dy = zeros(size(y)); % a matrix with arbitrarily many columns, rather than a column vector
dy = [y(2,:) .* y(3,:);...
-y(1,:) .* y(3,:);...
-0.51 .* y(1,:) .* y(2,:);];
function dy = fun4(t,y)
dy = [y(2,:) .* y(3,:);... % same as fun3()
-y(1,:) .* y(3,:);...
-0.51 .* y(1,:) .* y(2,:);];
(As a side remark: omitting the unnecessary memory allocation with zeros lets fun4 run slightly faster than fun3.)
Q: What about vectorizing with respect to the first argument?
A: For the ODE solvers, the ODE function is vectorized only with respect to the second argument. The boundary value problem solver bvp4c, however, does require vectorization with respect to the first and second arguments. [1]
The official documentation [1] provides further details on ODE-specific vectorization (see section "Description of Jacobian Properties").
[1] https://www.mathworks.com/help/releases/R2015b/matlab/ref/odeset.html