2017-05-19 61 views
1

我有一個運行速度慢的MATLAB函數,並且我確定了兩行計算密集的代碼。我還發現這兩行代碼並不相互依賴,可以並行化。我不知道什麼是並行的這兩行代碼的最佳方式,說我的代碼是這樣的:MATLAB中的並行編程

​​

假設一個是一個大的矩陣,那麼如何並行計算Y和X。 PARFOR是要做到這一點,例如一個辦法:

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

我覺得這種方式太天真了,我想知道是否有其他的方法來解決這個問題。

回答

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

感謝您的回答!我一直在玩批處理命令,並且非常慢。我發佈了另一個問題,你介意看看它嗎?謝謝! http://stackoverflow.com/questions/44081110/accelerate-batch-job-execution-in-matlab – Jason

+0

爲什麼使用'batch'而不是[parfeval](https://www.mathworks.com/help/distcomp/parfeval html的)? 'parfeval'的語法對我來說似乎更好。 –

1

您可以遵循類似下面....

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