Azzera filtri
Azzera filtri

How to call a function inside a parfor?

6 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

OCDER
OCDER il 18 Giu 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.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by