フィルターのクリア

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 Center および File ExchangeParallel for-Loops (parfor) についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by