How to solve an ODE with ode45 in a parfor loop?

I have the following code:
function [t,S] = solve_ode(fg_vars,tspan)
inital_conds = [0 0];
t = zeros(65,1);
S = zeros(65,2);
parfor i = 1:100
[t(:,i), S(:,i)] = ode45(@(t,s) fn(t,s,fg_vars),tspan,inital_conds)
end
t = t(:)
S = S(:)
end
Which gives me the following error:
Unable to perform assignment because the size of the left side is 65-by-1 and the size of the right side is 65-by-2.
I dont understand why this error occures, because when I try to calculate the ODE without the pafor loop, the produced solutions are of this size:
t = 65x1 double
S = 65x2 double
Thanks!

답변 (1개)

KSSV
KSSV 2020년 10월 29일
편집: KSSV 2020년 10월 29일

0 개 추천

[t(:,i), S(:,i)] = ode45(@(t,s) fn(t,s,fg_vars),tspan,inital_conds)
In the above t will be a column vector and S will be a column matrix with two columns. You cannot save like that. You can do
T = cell(100,1) ;
S = cell(100,1) ;
for i = 1:100
[t, s] = ode45(@(t,s) fn(t,s,fg_vars),tspan,inital_conds) ;
T{i} = t ;
S{i} = s ;
end
The above cannot be used with parfor...you cannot index the parfor loop.

댓글 수: 7

e_frog
e_frog 2020년 10월 29일
편집: e_frog 2020년 10월 29일
the goal was to accelarate the computation by using multiple cpu cores. So you are saying that it cant be done for an ode?
KSSV
KSSV 2020년 10월 29일
It can be done for ODE, but when you try to save, using an index. parfor will throw up error .
e_frog
e_frog 2020년 10월 29일
is there any way to save the solutions?
KSSV
KSSV 2020년 10월 29일
I think just using for loop, also is fine enoguh. It will not be slow..it should be fast enough.
e_frog
e_frog 2020년 10월 29일
if I try your version i get the error, that a double cant be converted to a cell. Also a for loop is way to slow, because i will expand the system to system of 2-3 ODEs. That will definitely need a parallelized computation.
KSSV
KSSV 2020년 10월 29일
Did you notice there is s and S. The one which is saved are initialized as cell S. And s is saved into S. You should have messed up with this.
e_frog
e_frog 2020년 10월 29일
I actually did have to switch a t with a T and it is running now. BUT: now matlab just does the same calculation 100 times, instead of splitting the one calculation for tspan up between the cpu cores. So now the calculation takes actually 100 times longer than without any loop at all. Thats not what i wanted. I NEED to use the parfor loop. How can I achieve that?

댓글을 달려면 로그인하십시오.

카테고리

질문:

2020년 10월 29일

댓글:

2020년 10월 29일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by