Reputation: 169
I want to write a fast matlab code to solve a system of ODE where parameters are space and time-dependent.Is there any way to solve it vectorically? following is the part of the code:
function dM=testfun(T,M,B1)
Mx=M(1);
My=M(2);
Mz=M(3);
dM=[My*B1(3)-Mz*B1(2);Mz*B1(1)-Mx*B1(3);Mx*B1(2)-My*B1(1)]+...
[-Mx/T2;-My/T2;(1-Mz)/T1];
here B1 is space-time dependent variable
main program :
clc;clear all;
tmin=0;
dt=rand(5,1);
tsteps=10;
B1x=rand(5,1);% time-dependent
jx=length(x);
z=-10:10;
jz=length(z);
M0=repmat([0; 0; 1],1,jz);
for p=1:jz
B1=[B1x;zeros(1,jx);10*z(jz)*ones(1,jx)]; % 3rd term is space dependent
for pp=1:jx
tspan=linspace(tmin,tmin+dt,tsteps);
[t,M(:,:,pp,p)]=ode45 (@(t,M) testfun(t,M,B1(:,jj)),tspan,M0(:,p));
tmin=tmin+dt;
end
end
Is there any way to vectorize the code? there is one problem with time-dependence- matlab has an inbuilt function interp1 for handling time dependent ODE but it takes too much time. check here How solve a system of ordinary differntial equation with time-dependent parameters My code will be development over this basic equation and it is important to save some time. Is there any way out? Thank you in advance.
The vectorization of the code can be found in the following post Vectorization of Matlab Code involving ODE solver at each iteration
The following post is also really helpful. How solve a system of ordinary differntial equation with time-dependent parameters
Upvotes: 0
Views: 984
Reputation: 119
Try to use LDE solver: https://www.mathworks.com/matlabcentral/fileexchange/60475-linear-differential-equation-solver-lde-m
I have good experience with this code.
Regarding vectorization/parallelization, MATLAB has no special options how to apply some special speedup trick on its generic ODE solvers.
Upvotes: 0