I need help to know how to work with variables defined outside parfor loops. I want to speed up a code that takes to much time when using higher number of elements.
I will try to explain it with an example. Let's suppose that initially I have a series of elements that will move randomly inside a loop and some calculations will take place according to the position of the elements.
Here is an example of the code:
% Variables
nElements = 5000; Ly = 2; vmax = 1;
time = 0.1:0.1:20;
x = -0.5+rand(nElements,1);
y = -Ly + Ly*rand(nElements,1);
zx = [];
zy = [];
rate = zeros(1,length(time));
vel = zeros(nElements,1);
vz = [];
% Loop
parfor ii=1:length(time)
nTimes = ii; % counter
vel = vmax.*(1-(y./Ly).^2) % elements will move according to this velocity profile
x = x + vel + randn(nElements,1);
y = y + vel + randn(nElements,1);
nZ = length(zx);
if ~isempty(zx) && ~isempty(zy)
vz = vmax.*(1-(zy./Ly).^2)
zx = zx + vz + randn(nZ,1);
zy = zy + vz + randn(nZ,1);
end
[x,y,zx,zy] = f(x,y,zx,zy); % function that uses the variables x and y; and if some conditions are met, creates a z element
rate(ii) = nZ;
end
I'm having problems with variables that are set outside the parfor loop and also due to the way variables are used. What I would like to know is how to use variables (that are defined outside) inside the parfor loop and how to work with them in functions if the variables are updated in every loop.
Thanks!
a = zeros(1,10); parfor it = 1:10 a(it) = someFunction(a(it-1)); endIt is clear that each iteration is dependent. But how can I modify this to run succesfully the code? - S. Perezparforinto a regularfor? - drhagen