MATLAB: Use variables (defined outside) inside parfor loop -
i need know how work variables defined outside parfor loops. want speed code takes time when using higher number of elements.
i try explain example. let's suppose have series of elements move randomly inside loop , calculations take place according position of elements.
here example of 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 move according 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 uses variables x , y; , if conditions met, creates z element rate(ii) = nz; end
i'm having problems variables set outside parfor loop , due way variables used. know how use variables (that defined outside) inside parfor loop , how work them in functions if variables updated in every loop.
thanks!
parallelizing on time (or system value @ each step depends on previous value) impossible, not in matlab, fundamentally.
fortunately, matlab use built-in multithreading of code shown here because code can vectorized along nelements
dimension. vectorized operations parallelized internally. slow part of particular code randn
, function both computationally expensive , typically sequential. if remove , @ processor usage, see multiple cores being used:
% variables nelements = 1000000; ly = 2; vmax = 1; time = linspace(0,1,100000); x = -0.5+rand(nelements,1); y = -ly + ly*rand(nelements,1); vel = zeros(nelements,1); % loop ii=1:length(time) vel = vmax.*(1-(y./ly).^2); x = x + vel; y = y + vel; end
Comments
Post a Comment