MATLAB中的并行程序设计

MATLAB中的并行程序设计,matlab,parallel-processing,parfor,Matlab,Parallel Processing,Parfor,我有一个运行缓慢的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

我有一个运行缓慢的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,可以为要在单个辅助进程上执行的每个函数创建一个批处理过程

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};

谢谢你的回答!我一直在玩批处理命令,但速度非常慢。我发了另一个问题,你介意看一下吗?谢谢为什么使用批处理而不是批处理?
parfeval
的语法对我来说似乎更好。