user1285419
user1285419

Reputation: 2225

any way to add a switch for spmd command in matlab?

I am using matlab2011 for parallel calculation with multiple cores, which in my code is simply implemented with the block SPMD END. However, for some times, I want to turn off the spmd in the program based on the input parameter. I try the following code, but it doesn't work

if (switchSpmdOn)
  spmd
end
% here I put my code for calculation in parallel or series
if (switchSpmdOn)
  end % this end is used to close the spmd block
end

I am wondering if there is anything like marco to turn off spmd in the code.

Upvotes: 3

Views: 409

Answers (1)

Yamaneko
Yamaneko

Reputation: 3563

You can pass the number of workers as a parameter to spmd. If the number of workers specified is 0, i.e.,

spmd(0)
   statement; %# block body
end

then MATLAB will execute the block body locally and create Composite objects, the same as if there is no pool available.

Example

switchSpmdOn = true;

%# set the number of workers
if (switchSpmdOn)
    workers = 3; 
    matlabpool(workers);
else
    workers = 0;
end

%# application. if 'workers' is 0, MATLAB will execute this code locally
spmd (workers)
    %# build magic squares in parallel
    q = magic(labindex + 2);
end

for ii=1:length(q)
  % plot each magic square
  figure, imagesc(q{ii});
end

if (switchSpmdOn)
    matlabpool close
end

Upvotes: 3

Related Questions