User defined functions with dynamic parameterisation in a parfor loops

1 view (last 30 days)
Thanks in advance for any assistance.
Is it OK to include a user defined function in a parfor loop, where the function definition changes with the loop indexation? Matlab is not identifying any errors, and from checking a few items manually, it seems to be correct. But I was unable to find anywhere online or in documentation that confirms Matlab handles this correctly or that functions are officially supported. Here is a simplified version to illustrate what I am asking about. The function is adjusted on each loop to run a different optimisation problem.
% Function parameters
FunctionParameters = [1, 2; 3, 4; 5, 6];
% Fmincon parameters
x0 = 1;
A =0;
b =0;
Aeq =0;
beq = 0;
lb = -1;
ub =1;
% Parfor optimisation loop
parfor n = 1:3
ExampleFunction = @(ExampleVariable) ExampleVariable * FunctionParameters(n,1) - FunctionParameters(n,2);
fun = ExampleFunction;
x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub)
Solutions(n)=x;
end
Solutions

Accepted Answer

Edric Ellis
Edric Ellis on 18 Jan 2021
This documentation for parfor notes various limitations - and also notes explicitly that you can create anonymous functions inside a parfor loop and use them, with some limitations. In your case, the limitations on sliced output variables do not apply since you're capturing input variables inside ExampleFunction.

More Answers (0)

Categories

Find more on Parallel for-Loops (parfor) in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!