Return values in a parfor loop

7 ビュー (過去 30 日間)
Wave
Wave 2020 年 5 月 14 日
編集済み: Benjamin Hezrony 2024 年 2 月 22 日
Heyhey,
at the moment my source code looks like this
ParForQueue = parallel.pool.DataQueue;
afterEach(ParForQueue,@AddStruct);
parfor m = 1:Anzahl
...
send(ParForQueue, Satz)
end
...
function [] = AddStruct(Satz)
global TabellenRueckgabe
...
end
My question is: how is it possible to avoid the global variable. I want to use the function like this instead of using global
function [TabellenRueckgabe] = AddStruct(Satz, TabellenRueckgabe)
TabellenRueckgabe(x) = Satz;
...
end

採用された回答

Edric Ellis
Edric Ellis 2020 年 5 月 15 日
Fundamentally, you need to "bind" a value in to the function that gets invoked by afterEach. The simplest way to do this is to use a nested function. Here's an example: in this case, the result vector has elements assigned when data queue messages are received:
function result = doStuff
q = parallel.pool.DataQueue;
% Pre-allocate the return value for the function
result = NaN(1, 20);
% This nested function modifies entries of 'result'
function nAccumulate(msg)
idx = msg(1);
val = msg(2);
result(idx) = val;
end
% Hook up our DataQueue to the nested function. The nested function
% handle can see and modify 'result'.
afterEach(q, @nAccumulate);
% Run the parfor loop, sending back updates.
parfor ii = 1:10
idx = randi(20);
val = rand();
% This will cause the idx'th element of 'result' to get the value
% 'val'.
send(q, [idx, val]);
end
end
  2 件のコメント
Wave
Wave 2020 年 5 月 15 日
Good idea. Thank you!
Benjamin Hezrony
Benjamin Hezrony 2024 年 2 月 22 日
編集済み: Benjamin Hezrony 2024 年 2 月 22 日
Is there a way to return “result” without using a nested function?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeBackground Processing についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by