Access to variables of function in which calling function is nested

조회 수: 3 (최근 30일)
I have this function:
function[measure1,minNumSensors1,feasible] ...
= measureAlg1FUN(numOfSensorstoTurnOn,sigmav,sigma_theta,...
sigmax,Dthres,Pmax,sourcePos,FCPos,sensorPos)
which contains a call to fmincon:
[P,fval]=fmincon(@objfun,P0,[],[],[],[],lb,ub,@confun,options);
When calling measureAlg1FUN, I get an error that the variables within this function are not accessible. These are needed for example in the constraint function defined as:
function[c,ceq]=confun(P)
a1=evalin('base','RvAlg');
a2=evalin('base','sigmax');
a3=evalin('base','sigma_theta');
a4=evalin('base','R_thetaAlg');
a5=evalin('base','RxAlg');
a6=evalin('base','Dthres');
Dp=diag(sqrt(P)/a2);
c=a3^2-a4*Dp*(Dp*a5*Dp+a1)^(-1)*Dp*a4'-a6;
ceq=[];
end
You can see that I have input the required variables using evalin from the base workspace. Of course, these variables do not exist within the base workspace, but within the workspace of function measureAlg1FUN. Changing the evalin argument from 'base' to 'caller', with the intent of having it access the variables in the caller function measureAlg1FUN, does not work either. I think this is because the caller is actually fmincon.
What can I do? Any help would be appreciated!

채택된 답변

Geoff Hayes
Geoff Hayes 2016년 4월 4일
harleykitten - if you want your confun function to be able to access the local variables defined in measureAlg1FUN, then you should nest confun within it.
For example, in the measureAlg1FUN.m file you would do
function[measure1,minNumSensors1,feasible] ...
= measureAlg1FUN(numOfSensorstoTurnOn,sigmav,sigma_theta,...
sigmax,Dthres,Pmax,sourcePos,FCPos,sensorPos)
% do something
% call fmincon
[P,fval]=fmincon(@objfun,P0,[],[],[],[],lb,ub,@confun,options);
% nest confun
function[c,ceq]=confun(P)
Dp=diag(sqrt(P)/sigmax);
c=sigma_theta^2-R_thetaAlg*Dp*(Dp* RxAlg*Dp+RvAlg)^(-1)*Dp* R_thetaAlg'-Dthres;
ceq=[];
end
end
Try the above and see what happens!

추가 답변 (1개)

Steven Lord
Steven Lord 2016년 4월 4일
If you're not modifying those variables (and you shouldn't be, as it could confuse the solver) you should pass them into the constraint function as additional parameters. The documentation for FMINCON links to a page describing several techniques by which you can do this.

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by