필터 지우기
필터 지우기

How to call a function inside a parfor?

조회 수: 11 (최근 30일)
Nikita Agrawal
Nikita Agrawal 2018년 6월 18일
댓글: Vitor Cardoso 2020년 11월 21일
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.

채택된 답변

OCDER
OCDER 2018년 6월 18일
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
Vitor Cardoso
Vitor Cardoso 2020년 11월 21일
Thank YOU ! This was life saving!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Parallel for-Loops (parfor)에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by