MATLAB 并行计算

主要函数:parfor

并行 for 循环

说明:

parfor LoopVar = InitVal:EndVal; Statements; end

在生成的 MEX 函数中或在共享内存多核平台上并行运行的 C/C++ 代码中创建一个循环。

parfor 循环对 InitVal 和 Endval 之间的 LoopVar 值执行 Statements。LoopVar 指定由整数值组成的向量,这些值按 1 递增。

parfor (LoopVar = InitVal:EndVal, NumThreads); Statements; end

在创建并行 for 循环时,最多使用 NumThreads 个线程。

写法案例:

parfor rowIndex=1:regionRow
    point=cell(regionCol,4);
    for colIndex=1:regionCol
        disp(['rowIndex =',num2str(rowIndex),'colIndex =',num2str(colIndex)]);
        mdl = stepwiselm(full,pointLpmay{rowIndex,1}{colIndex,1},'quadratic','Verbose',0);
        point{colIndex,1}=mdl.Formula.Terms;            % 方程的项与结构
        point{colIndex,2}=mdl.Coefficients.Estimate;    % 方程项的系数
        point{colIndex,3}=mdl.Rsquared.Ordinary;    % 判定系数
        point{colIndex,4}=mdl.Rsquared.Adjusted;    % 调整判定系数
    end
    pointLpmaA{rowIndex,1}=point;
end

注意:

此种方法开启并行默认使用最大线程数,而MATLAB默认允许的最大线程数为12,若计算机的真核数量超过12,可以用以下方式进行扩展:

%%%   设置MATLAB可以联通24个线程(否则默认最大线程为12)   %%%
c = parcluster('local');
c.NumWorkers = 24;
parpool(c, c.NumWorkers);

  

已经开启并行工具箱之后,若要重新开启,需要先关闭之前的并行,再开新的,关闭方法如下:

delete(gcp('nocreate'))

 

参考资料:

https://ww2.mathworks.cn/help/coder/ref/parfor.html?s_tid=srchtitle

https://blog.csdn.net/enjoyyl/article/details/41929033

https://www.mathworks.com/matlabcentral/answers/131618-why-does-my-matlab-2014a-only-start-12-workers-when-i-ask-for-more

 

posted @ 2020-08-25 14:52  CollinsLi  阅读(1784)  评论(0编辑  收藏  举报