在matlab中为spmd命令添加开关的任何方法?

时间:2012-07-19 22:02:52

标签: parallel-processing matlab

我正在使用matlab2011进行多核并行计算,我的代码中只使用块SPMD END实现。但是,有时候,我想根据输入参数关闭程序中的spmd。我尝试以下代码,但它不起作用

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

我想知道是否有像marco这样的东西可以在代码中关闭spmd。

1 个答案:

答案 0 :(得分:3)

您可以将工作人员数量作为参数传递给spmd。如果指定的工作人员数量为0

spmd(0)
   statement; %# block body
end

然后MATLAB将在本地执行块体并创建Composite对象,就像没有可用的池一样。

示例

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