Effacer les filtres
Effacer les filtres

How to call a function inside a parfor?

11 vues (au cours des 30 derniers jours)
Nikita Agrawal
Nikita Agrawal le 18 Juin 2018
Commenté : Vitor Cardoso le 21 Nov 2020
I have a loop that runs fmincon. Fmincon has another function inside it i.e. the objective function. Please help me with how to I write the objective function.
Objective function:
function [obj grad] = phi(y)
obj = (yraw-y)'*Vinv*(yraw-y);
grad = -2*Vinv*(yraw-y);
end
I have a full size matrix call raw of size 100*39 this is how the parfor loop looks like
parfor s = 1:length(raw)
yraw = raw(s,:)';
Vinv = eye(39);
[xrec,fval,exitflag,output,lambda,grad,hessian] = fmincon(@phi,yraw,Aineq,bineq,At(s).Aeq, b(s).beq,[],[],[],options);
end
When it is run, I get the following error:
Error using phi An UndefinedFunction error was thrown on the workers for 'yraw'. This might be because the file containing 'yraw' is not accessible on the workers. Use addAttachedFiles(pool, files) to specify the required files to be attached. See the documentation for 'parallel.Pool/addAttachedFiles' for more details.
Error in fmincon (line 555) [initVals.f,initVals.g] = feval(funfcn{3},X,varargin{:});
Error in DR (line 66) parfor s = 1:length(raw)
Caused by: Failure in initial objective function evaluation. FMINCON cannot continue. Undefined function or variable 'yraw'. Failure in initial objective function evaluation. FMINCON cannot continue.

Réponse acceptée

OCDER
OCDER le 18 Juin 2018
1. phi does not know what yraw and Vinv are. To fix, do this:
function [obj grad] = phi(y, yraw, Vinv) %Pass yraw and Vinv
obj = (yraw-y)'*Vinv*(yraw-y);
grad = -2*Vinv*(yraw-y);
end
2. Your fmincon needs to pass on yraw and Vinv to your phi function. To fix, do this:
[xrec,fval,exitflag,output,lambda,grad,hessian] = fmincon(@(x) phi(x, yraw, Vinv),yraw,Aineq,bineq,At(s).Aeq, b(s).beq,[],[],[],options);
end
3. Your outputs for each parfor iteration aren't being saved correctly. To fix, do something like:
[xrec{s}, fval{s}, ...] %save each output to a cell array.
  1 commentaire
Vitor Cardoso
Vitor Cardoso le 21 Nov 2020
Thank YOU ! This was life saving!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Parallel for-Loops (parfor) dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by