How to call a function inside a parfor?
11 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Parallel for-Loops (parfor) 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!