MATLAB: Parallel ODE solve using parfor-loop

odeparallel computingParallel Computing Toolboxparfor

Hello, I'm trying to solve my parallel ODE system, because very a small step and high tolerance are necessary here. Here is the code:
n = 4
matlabpool('open',n)
X0=[0.0046 10.9820 15.3579]
tend=5000;
parfor i=0:100
options = odeset('RelTol', 1e-2,'MaxStep', 1e-4);
[T(i*50:(i+1)*50),X(i*50:(i+1)*50)] = ode45(@rightpart,[50*i 50*(i+1)],X0,options);
end
matlabool close;
figure
plot(T,X(:,1),'-',T,X(:,2),'-.',T,X(:,3),'.')
figure
plot3(X(:,1),X(:,2),X(:,3))
end
Matlab doesn't allow to use [T,X] after parfor-loop. How can I modify this code? Or are there any other solutions for this problem?

Best Answer

The problem is that PARFOR doesn't know how to 'slice' your variables T and X because the indexing expression you're using is too complicated. There are more details on this page, but basically I think it should work to do this:
% pre-allocate rectangular T and X.
T = zeros(50, 101);
X = zeros(50, 101);
parfor i = 1:101
...
% Assign whole columns of T and X using 'i' as the slicing index
[T(:, i), X(:, i)] = ode45(...);
end
% Convert T and X back to single columns
T = T(:);
X = X(:);