Search code examples
matlabparfor

will same variable name cause conflict in parfor


I have a basic code like this :

parfor i=1:8
    [t,y]=ode15s(@rate,tspan,cin,options,i); % the option i is evaluated in the rate function
    figure(1)
    subplot(3,3,i+1)
    plot(t,y)
    hold on
end

Will any conflict arise because the variable name y is same in all iterations ?


Solution

  • No, every worker has its unique namespace.

    However, a worker cannot open figures that display on the client (thanks for the reminder, @Edric), so everything after the call to ode15s will not produce any useful result.

    To move the plotting outside the parfor loop, you can do the following (there are more efficient solutions, this one will work for sure):

    tCell = cell(8,1);
    yCell = cell(8,1);
    parfor i=1:8
        [tCell{i},yCell{i}]=ode15s(@rate,tspan,cin,options,i); % the option i is evaluated in the rate function
    
    end
    
    figure(1)
    for i=1:8
       subplot(3,3,i+1)
       plot(tCell{i},yCell{i})
       hold on
    end