MATLAB 中的并行编程

parallel programming in MATLAB

我有一个 MATLAB 函数 运行 很慢,我已经确定了两行计算密集型代码。我还发现这两行代码互不依赖,可以并行化。我想知道并行这两行代码的最佳方法是什么,假设我的代码是这样的:

function [y,x] = test1(a)
    y = exp(a);
    x = sin(a);
end

假设a是一个大矩阵,那么如何并行计算y和x。 Parfor 是一种方法,例如:

parfor i = 1:2
    if i == 1
        y = exp(a);
    else
        x = sin(a);
    end
end

感觉这种方式太幼稚了,想知道有没有其他方法可以解决

您可以按照以下内容进行操作....

funcs = {@exp,@sin} ;
args = {2,pi/4} ;
sols = cell(1,2) ;
parfor n = 1:2
    sols{n}=funcs{n}(args{n});
end
M = sols{1} ; N = sols{2} ;

如果您不想使用 parfor,您可以为每个要在单个 worker 上执行的函数创建一个批处理。

a = 10;
% starts execution on separate workers
exp_handle = batch(@exp,1,{a});
sin_handle = batch(@sin,1,{a});

% waits ultil the first is complete and gets the result
wait(exp_handle);
yc = fetchOutputs(exp_handle); % cell

% waits until the second is complete and gets the result
wait(sin_handle);
xc = fetchOutputs(sin_handle); % cell

y = yc{1};
x = xc{1};