Access to variables of function in which calling function is nested

4 次查看(过去 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