How to use parfor instead of for in this function

1 view (last 30 days)
In this function how can I replace "for" by "parfor". I get this error when I do so:
"The parfor loop cannot run due to the way variable 'y' is defined."
function [x,y] = Euler(ODEfile,xi,xf,h,yi,varargin)
% EULER Solves a set of ordinary differential equations by
% the modified Euler (predictor-corrector) method.
%
% [X,Y]=EULER('F',XI,XF,H,YI) solves a set of ordinary
% differential equations by the modified Euler (the Euler
% predictor-corrector) method, from XI to XF.
% The equations are given in the M-file F.M.
% H is the length of interval and
% YI is the vector of initial values of the dependent variable at XI.
%
% [X,Yl=EULER('F', XI, XF,H,YI, P1,P2,. . . ) allows for additional
% arguments which are passed to the function F(X,Pl,P2,. . . ) .
if (isempty (h) || h == 0)
h = linspace(xi,xf);
end
yi = (yi (:).')' ;
x = [xi:h:xf];
if x(end) ~= xf
x(end+1) = xf;
end
d = diff (x);
y(:,1) = yi;
% Solution
for i = 1:length(x)-1
% Predictor
y(:,i+1)=y(:,i) + d(i) * feval(ODEfile,x(i), y(:,i), varargin{:});
% Corrector
y(:,i+1) =y (:,i) + d(i) * feval(ODEfile, x(i+1), y(:,i+1), varargin{:}) ;
end

Accepted Answer

Walter Roberson
Walter Roberson on 20 Nov 2020
That is not possible. The output when i=2 depends on y(:,2) having been set properly, but y(:,) has not been assigned to until i=1 is finished.
There are particular functions where it might be possible to do some of the work in parallel and then do fix-ups, but I suspect that those cases work out the same as the functions that there are known analytical solutions for, and you are either given the analytical solution or can find it using the symbolic toolbox.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!