Understanding nested function reference in parfor loop
4 ビュー (過去 30 日間)
古いコメントを表示
I came accross this sentence in MATLAB doc:
The body of a parfor-loop cannot make reference to a nested function. However, it can call a nested function by means of a function handle.
Can someone please explain what this means?
2 件のコメント
Jonathan Chin
2017 年 10 月 19 日
Look at this examples where I am creating a function handle for my nested function.
function out=parforTest(in)
out = zeros(1,4);
tmp=@(x)nestedFunc(in,x);
parfor ii=1:4
out(ii)=feval(tmp,ii)
end
function outv= nestedFunc(in,var)
outv = in+var;
end
end
回答 (1 件)
Himanshu
2024 年 12 月 10 日
Hey,
The sentence mentioned by you from the documentaiton points out a limitation of the 'parfor' loop, which is that it cannot directly reference nested functions within its loop body. Instead, you can call a nested function using a function handle, which is like a reference or pointer to a function. For example:
function mainFunction()
% Nested function
function result = nestedFunction(x)
result = x^2;
end
% Create a function handle
nestedHandle = @nestedFunction;
% Use parfor with the function handle
parfor i = 1:5
results(i) = nestedHandle(i);
end
disp(results);
end
In the code above, inside the parfor loop, you call the nested function using the handle nestedHandle(i). This approach bypasses the restriction, allowing the nested function to be used in parallel computations.
In simple terms, while parfor can't directly use nested functions, creating a function handle allows you to call them indirectly, enabling parallel execution.
Hope this help!
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!